我有一个三层应用程序。每个部分都与我的解决方案的另一部分有依赖关系。我曾经在MVC项目中实现了IDependencyResolver
。这是一种错误的方式,因为它会导致违反层分离的架构规则。我的MVC项目引用了DAL层。这是一种糟糕的编码习惯。我知道我可以创建一个单独的类库项目。它将引用我的解决方案的任何其他项目。它将解决所有的依赖关系。我听说这不是最好的方法。有一个更好的办法。我的解决方案的每个项目都应该解决它拥有的依赖关系。我不明白如何把它放在一起。所以我发现这篇有用的文章:Dependency Injection Best Practices in an N-tier Modular Application,但它似乎太困难和复杂。有另一种方法吗?我有一个类似的解决方案结构。 UserRepository
返回一个请求的用户。如何在N层图层应用程序中实现IDependencyResolver?
public interface IUserRepository
{
IEnumerable<UserEntity> GetAll();
}
public class UserRepository : IUserRepository
{
public IEnumerable<UserEntity> GetAll()
{
// some code
}
}
UserService
可以有几个不同的依赖关系。
public interface IUserService
{
IEnumerable<UserModel> GetAll();
}
public class UserService : IUserService
{
private readonly IUserRepository userRepository;
private readonly ISecondRepository secondRepository;
private readonly IThirdRepository thirdRepository;
public UserService(IUserRepository userRepository, ISecondRepository secondRepository, IThirdRepository thirdRepository)
{
this.userRepository = userRepository;
this.secondRepository = secondRepository;
this.thirdRepository = thirdRepository;
}
public IEnumerable<UserModel> GetAll()
{
// some code
}
}
最后UserController
构造函数可能有很多不同的依赖关系。
我的问题是关于什么是正确的,最简单的方法来解决这些依赖关系,避免违反架构规则?
想想运行时的层分离规则。当应用程序由依赖解析器引导时,如果您已正确映射解析器,它将遵循这些规则。看看这个答案http://stackoverflow.com/questions/40401900/bootstrapping-unity-composition-root-location/40403875#40403875 –
可能重复[Ioc/DI - 为什么我必须引用所有层/组件in entry application?](http://stackoverflow.com/questions/9501604/ioc-di-why-do-i-have-to-reference-all-layers-assemblies-in-entry-application) – NightOwl888