I have gone through the link:
https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection
and learnt that how I can use dependency injection for Web API.
As mentioned in the above link I can use Startup (Startup.cs) class for dependency injection inside API layer. But how can achieve dependency injection for the .NET Core Class Library. Below is the screenshot how I am adding a class library.
And my project structure is
In the project “DataManagement.Repository” I have written a class “UserRepository” and in the project “DataManagement.Repository.Interfaces” written an Interface “IUserRepository”.
In the project “DataManagement.Business” I have written a class “UserManager”
class UserManager { private IUserManager _userManager; public UserManager(IUserManager userManager) { _userManager = userManager; } }
As you can see that I am trying to achieve dependency injection through the constructor.
But I am not sure that what changes need to be done for enabling dependency injection inside .NET Core Class Library (.NET Standard).
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.
NET Core, you need to use the . NET Framework. You can now reference . NET Framework libraries from .
Enterprise Library is a good example of a library that really takes advantage of a dependency injection container without being hard coupled to one.
You don't have to do anything in your class library. Only the main application has a composition root (earliest point in an application lifecycle you can set up your object graph).
This happens in Startup.cs
in your ASP.NET Core application. There you also register your dependencies:
services.AddScoped<IUserManager,UserManager>();
That's it. Class libraries don't have a composition root. Neither they should, because you can't use them without an application and the IoC Container used is a choice of the application not of the library.
You can however provider convenience methods to do this registrations, like the AddXxx
method common in ASP.NET Core or some kind of module system, like in 3rd party IoC containern like Autofac or Castle Windsor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With