asp.net核心依赖关系传递依赖关系

时间:2017-08-04 14:00:50

标签: c# asp.net-core

我试图将依赖注入到控制器内部使用的类中,

我有

//Startup.cs
public void ConfigureServices(IServiceCollection services){
    services.AddMvc();//IDocumentService is a WCF service from our legacy stack
    services.AddScoped(typeof(IDocumentService),typeof(DocumentServiceClient));
}
//Controller.cs
[Route("api/eci/test/[action]")]
public class Controller{
    private IDocumentService injectedDocService;
    public Controller(IDocumentService client){
        injectedDocService=client;
    }
    [HttpPost({"id"})]
    public void ingestedDocs(string id){
        new Logic(injectedDocService).ingest(id);
    }
}
//Logic.cs
public class Logic{
    private IDocumentService injectedDocServiceActualTarget;
    public Logic(IDocumentService injected2){
        injectedDocServiceActualTarget=injected2;
    }
    public void injest(string id){
        injectedDocServiceActualTarget.doWork(id);
    }
}

将它注入目标类的父级似乎有点多余。这是正确的做事方式吗?

2 个答案:

答案 0 :(得分:1)

您需要注册Logic,然后将其注入控制器。 DocumentService将被注入Logic

依赖注入背后的想法是实现IoC(控制反转)原则。在您的示例中,它只是部分的,因为您在控制器中显式实例化Logic。如果要正确执行依赖项反转 - 所有依赖项都需要作为构造函数参数传递。

答案 1 :(得分:1)

您应该在界面后面抽象Logic,只展示被依赖者使用的成员。

public interface ILogic {
    void injest(string id);
}

让Logic类派生自抽象。

//Logic.cs
public class Logic : ILogic {
    private readonly IDocumentService injectedDocServiceActualTarget;

    public Logic(IDocumentService injected2) {
        this.injectedDocServiceActualTarget=injected2;
    }

    public void injest(string id) {
        injectedDocServiceActualTarget.doWork(id);
    }
}

Controller现在应该只显式依赖ILogic接口

//Controller.cs
[Route("api/eci/test/[action]")]
public class Controller {
    private readonly ILogic service;

    public Controller(ILogic service) {
        this.service = service;
    }

    [HttpPost({"id"})]
    public void ingestedDocs(string id) {
        service.ingest(id);
    }
}

最后要做的就是在服务集合中注册所有依赖项。

//Startup.cs
public void ConfigureServices(IServiceCollection services){
    services.AddMvc();
    services.AddScoped<IDocumentService, DocumentServiceClient>();
    services.AddScoped<ILogic, Logic>();
}

所以现在当调用控制器时,所有依赖关系都将被解析并注入其各自的家属。