Please note that below post would be more clear for those who already know what Dependency injection is.
As we all know that things has been little changed in .Net core and things has also been changed the way we suppose to register all of our services that we are going to use as DI.
Suppose you have one HomeController and in that controller you want to inject a service let us say MyService.
In controller it would look like as it was used to :
public HomeController(IMyServcie myService)
{
…
}
And in a class library called MyService, it would look like as below:
public class MyService : IMyService
{
private readonly IMyRepository _myRepository;public MyService(IMyRepository myRepository)
{
_myRepository = myRepository;
}
…….
}
You can even inject services into views using @inject. I have already written post on that which is here.
So now you might be wondering like where should we register this.
ConfigurationServices is your composition root so that’s where you register you services.
So it would be as below:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();// Add application services.
services.AddScoped<IMyService, MyService >();
}
Okay so above scenario is ideal scenario but you might be having some questions as below:
- What if you have some of your code written outside of your MVC application?.
- Also what if you do not want to bloat the ConfigurationServices method with lots of AddScoped lines of code for other layers like Repository layer and Service layer?
- What to do if I need to do in my other layers (Repository and Service) to first register them here (both are .NET Core class library projects) and then wire those containers into the parent container?
For that you just need to create different Extension methods in different layers which targets IServiceCollection as below:
public static IServiceCollection AddMyServices(this IServiceCollection services) {
services.AddMyRepositories();
services.AddScoped<IMyService, MyService>();
//…add other services
}
And in Repository layer it would have a extension method as below:
public static IServiceCollection AddMyRepositories(this IServiceCollection services) {
services.AddScoped<IMyRepository, MyRepository>();
//…add other Repositories
}
And now you could just as easily call the AddMyRepositories() in the AddMyServies extension method as opposed to the main project itself:
public void ConfigureServices(IServiceCollection services) {
//…other codeservices.AddMyServices();
//…other code
}
That is it!
Happy coding!