c# - 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
,我必须将项目引用添加到MyDomain和MyService类库。这会将我的 API 项目中的依赖项添加到MyService项目中,这应该通过 IoC 模式来避免。我确实在stackoverflow中查看了各种帖子,但没有找到明确的答案。那么如何在我的 API 项目中设置MyService
为实现而不引用MyServiceIMyService
项目?您在回答中使用哪个 IoC 容器并不重要(ninject、unity、...)
解决方案
Ok, after more research, I come to solution which is fine. Back to whiteboard:
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:
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 :)
推荐阅读
- ios - 将 NumberFormatter 与 C 格式一起使用(例如“%6.3f”)
- javascript - 无法在 Chrome 中打开新窗口
- pagination - 通过 Boto3 进行 DynamoDB 分页,NextToken 不存在,但 LastEvaluatedKey 存在?
- reactjs - 如何在反应中从状态数组中添加或删除项目
- c++ - 如何在卡萨布兰卡为外部连接设置 listener() 设置?
- java - 类文件的版本错误
- c++ - 为什么当我声明复制初始值设定项被删除时,使用等于运算符的声明是错误的
- android - android studio 3.4.1 的 Jarsigner 问题
- java - 从下向上动画片段,在上一个片段之上
- regex - 正则表达式从选择中排除空格