我有一个控制器的构造函数,我想在其中实例化一个对象,该对象可以通过依赖注入来访问存储库。
像这样:
ContactController.cs:我收到一个错误,因为我没有通过IContactRepository
private ContactOperationsFacade contactOperator;
ContactController(){
contactOperator = new ContactOperationsFacade(//I want to use DI here);
}
ContactOperationsFacade.cs:
private readonly IContactRepository contactRepository;
public ContactOperationsFacade(IContactRepository contactRepositor){
this.contactRepository = contactRepository;
}
如何在仍使用DI作为存储库的控制器的构造函数中实例化此ContactOperationsFacade对象?
答案 0 :(得分:2)
在asp.net核心中,只要范围允许,您就可以进行DI链接。因此,如果A依赖于B并且控制器想要A,则只需将A和B都添加到di容器中(代码的ConfigureServices部分),然后容器就会知道。
在这里https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1
了解更多答案 1 :(得分:1)
ContactController
应该跟随The Explicit Dependencies Principle
方法和类应明确要求(通常通过方法参数或构造函数参数)它们所需的任何协作对象,以使其正常运行。
类也应依赖抽象,而不应与具体概念耦合。
所以假设类似
public class ContactOperationsFacade: IContactOperationsFacade { //<-Note interface/contract
private readonly IContactRepository contactRepository;
public ContactOperationsFacade(IContactRepository contactRepositor){
this.contactRepository = contactRepository;
}
//...
}
控制器应取决于外观从其派生的抽象
public class ContactController: Controller {
private readonly IContactOperationsFacade contactOperator;
public ContactController(IContactOperationsFacade contactOperator){
this.contactOperator = contactOperator;
}
//...
}
并假定所有接口和实现都已在DI容器中注册。
services.AddScoped<IContactOperationsFacade, ContactOperationsFacade>();
所有依赖项都已注册后,服务提供商应在激活控制器时解决它们。