I am trying to do WEB API project in .NET Core 3.1 with dependancy injection and in Startup
class, of my web api project I added this:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IMyService, MyService.MyService>(); // <- added MyService as implementation
}
So after that I was able to use service in my controller class
public class BPMController : ControllerBase
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
}
That's fine. However IMyService
is defined in another class library which I called MyDomain and MyService
is defined in class library which I called MyService . Now in order to be able to configure MyService
as implementation if IMyService
in my API project I had to add project reference to both MyDomain and MyService class library. This adds dependency in my API project to MyService project which should be avoided by IoC pattern. I did look at various posts here in stackoverflow, but nowhere I found clear answer. So how to set MyService
as implementation of IMyService
in my API project without referencing MyService project? It does not matter which IoC container you use in answer (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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.