简体   繁体   English

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

[英]Using Dependency Injection with .NET Core Class Library (.NET Standard)

I have gone through the link: 我已经通过链接:

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

and learnt that how I can use dependency injection for Web API. 并了解到如何为Web API使用依赖注入。

As mentioned in the above link I can use Startup (Startup.cs) class for dependency injection inside API layer. 如上面的链接所述,我可以使用Startup(Startup.cs)类在API层内部进行依赖注入。 But how can achieve dependency injection for the .NET Core Class Library. 但是如何实现.NET核类库的依赖注入。 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”. 在项目“DataManagement.Repository”中,我编写了一个类“UserRepository”,并在项目“DataManagement.Repository.Interfaces”中编写了一个接口“IUserRepository”。

In the project “DataManagement.Business” I have written a class “UserManager” 在“DataManagement.Business”项目中,我写了一个类“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). 但我不确定在.NET Core类库(.NET标准版)中启用依赖项注入需要做哪些更改。

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. 这发生在ASP.NET Core应用程序的Startup.cs中。 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. 它们都不应该,因为如果没有应用程序就无法使用它们,并且使用的IoC容器是应用程序的选择,而不是库的选择。

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. 但是,您可以提供便捷方法来执行此注册,例如ASP.NET Core中常见的AddXxx方法或某种模块系统,例如Autofac或Castle Windsor等第三方IoC容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM