将依赖注入与 .NET Core 类库(.NET Standard)结合使用 [英] Using Dependency Injection with .NET Core Class Library (.NET Standard)

查看:32
本文介绍了将依赖注入与 .NET Core 类库(.NET Standard)结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了链接:

我的项目结构是

在DataManagement.Repository"项目中,我编写了一个UserRepository"类,并在DataManagement.Repository.Interfaces"项目中编写了一个接口IUserRepository".

在DataManagement.Business"项目中,我编写了一个UserManager"类

class UserManager{私有 IUserManager _userManager;公共用户管理器(IUserManager 用户管理器){_userManager = 用户管理器;}}

如您所见,我正在尝试通过构造函数实现依赖注入.

但我不确定在 .NET Core 类库(.NET Standard)中启用依赖注入需要做哪些更改.

解决方案

您无需在类库中执行任何操作.只有主应用程序有一个组合根(应用程序生命周期中的最早点)可以设置您的对象图).

这发生在 ASP.NET Core 应用程序的 Startup.cs 中.您还可以在那里注册您的依赖项:

services.AddScoped();

就是这样.类库没有组合根.它们也不应该,因为没有应用程序就不能使用它们,并且所使用的 IoC 容器是应用程序的选择,而不是库的选择.

然而,您可以提供方便的方法来进行此注册,例如在 ASP.NET Core 或某种模块系统中常见的 AddXxx 方法,例如在 Autofac 或 Castle Windsor 等 3rd 方 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.

这篇关于将依赖注入与 .NET Core 类库(.NET Standard)结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆