Using Dependency Injection Using the .NET Core Class Library (.NET Standard)

I followed the link:

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection

and found out how I can use dependency injection for the web API.

As mentioned in the link above, I can use the Startup class (Startup.cs) to inject dependencies inside the API level. But how can you achieve dependency injection for the .NET Core Class library. Below is a screenshot of how I am adding a class library. enter image description here

And my project structure

enter image description here

In the project "DataManagement.Repository" I wrote the class "UserRepository", and in the project "DataManagement.Repository.Interfaces" the interface "IUserRepository" is written.

In the project "DataManagement.Business" I wrote the class "UserManager"

class UserManager { private IUserManager _userManager; public UserManager(IUserManager userManager) { _userManager = userManager; } } 

As you can see, I'm trying to inject dependencies through the constructor.

But I'm not sure what changes need to be made to include dependency injection inside the .NET Core Class Library (.NET Standard).

+7
dependency-injection asp.net-core visual-studio-2017 .net-core asp.net-core-webapi
source share
1 answer

You do not need to do anything in your class library. Only the main application has a composite root (the earliest point in the application life cycle you can customize your object graph).

This happens in Startup.cs in your ASP.NET Core application. There you also register your dependencies:

 services.AddScoped<IUserManager,UserManager>(); 

What is it. Class libraries do not have a composition root. Neither they, nor because you cannot use them without an application, and the IoC Container used is the choice of the application, not the library.

However, you can use vendor convenience methods for these registrations, such as the AddXxx method, which is common in the ASP.NET kernel or some other modular system, such as a third-party IoC such as Autofac or Castle Windsor.

+9
source share

All Articles