首页 > 解决方案 > Net Core API 依赖注入,无需在 API 项目中引用存储库库

问题描述

我正在尝试在 .NET Core 3.1 中使用依赖注入和在Startup课堂上做 WEB API 项目,在我的 web api 项目中我添加了这个:

public void ConfigureServices(IServiceCollection services)
{
   services.AddControllers();
   services.AddScoped<IMyService, MyService.MyService>(); // <- added MyService as implementation
}

所以在那之后我可以在我的控制器类中使用服务

public class BPMController : ControllerBase
{
  private readonly IMyService _myService;

  public MyController(IMyService myService)
  {
    _myService = myService;
  }
}

没关系。但是IMyService在另一个我称为MyDomain的类库中定义,并MyService在我称为MyService的类库中定义。现在,为了能够在我的 API 项目中配置MyService为实现IMyService,我必须将项目引用添加到MyDomainMyService类库。这会将我的 API 项目中的依赖项添加到MyService项目中,这应该通过 IoC 模式来避免。我确实在stackoverflow中查看了各种帖子,但没有找到明确的答案。那么如何在我的 API 项目中设置MyService为实现而不引用MyServiceIMyService项目?您在回答中使用哪个 IoC 容器并不重要(ninject、unity、...)

标签: c#.net-coredependency-injectionasp.net-core-webapi

解决方案


Ok, after more research, I come to solution which is fine. Back to whiteboard:

enter image description here

In this situation although, I'm using DI, I can instantiate my service with

Service myService = new Service();

which I ultimately wanted to disable (so that no programmer can make that mistake). This could be done by adding another assembly which would contain references to service projects. This assembly (and only this, not services), will be referenced from API project, and role of this assembly is to do dependency injection instead that API project is doing it. Something like this:

enter image description here

What is benefit of this approach? Well, now programmers can't do:

Service myService = new Service(); //we missing Service class

and are forced to instantiate services properly (using DI). That was what I wanted :)


推荐阅读