且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在.NET Core类库(.NET标准)中使用依赖注入

更新时间:2023-10-19 08:35:46

您无需在类库中做任何事情。只有主应用程序具有组合根(您在应用程序生命周期中的最早时间可以设置对象图)。



这种情况发生在ASP.NET Core应用程序的 Startup.cs 中。在那里,您还注册了依赖项:

  services.AddScoped< IUserManager,UserManager>(); 

就是这样。类库没有复合词根。它们都不应该,因为没有应用程序就无法使用它们,并且所使用的IoC容器是应用程序的选择,而不是库的选择。



不过,您可以提供方便的方法来进行此注册,例如ASP.NET Core中常见的 AddXxx 方法或某种模块系统,例如Autofac或Castle Windsor等第三方IoC容器中。


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).

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.