且构网

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

如何在多项目解决方案中使用.net核心依赖项注入?

更新时间:2023-02-16 13:35:58


...在ASP.NET核心项目中,我们具有ConfigureServices ...以注册我们的接口及其实现...如果您在同一项目中都具有类,那么这很好,但是如果我有多个项目怎么办?

...in ASP.NET core project[s] we have ConfigureServices... to register our interfaces and their implementations... This is good if you have classes all in the same project, but what if I have multi projects?

不要紧,您有多个项目。遵循相同的原则:

It doesn't matter that you have multi projects. The same principle applies:

将合成根放在应用程序中,并尽可能靠近入口点。

让我们假设您有一个引用多个类库的应用程序。在应用程序的启动类中,使用 ConfigureServices 注册所有依赖项。在每个类库项目中,使用构造函数注入。没关系,您的类是否位于相同或不同的项目中。

Lets assume that you have a single application that references several class libraries. In your application's Startup class, use ConfigureServices to register all of the dependencies. In each of the class library projects, use constructor injection. It does not matter whether your classes live in the same or in different projects.


OK将您在ConfigureServices(IServiceCollection services)中拥有的IServiceCollection传递给以前创建的RegisterationMethod,以这种方式,您正在使用与ASP.NET相同的服务集合。

OK pass IServiceCollection you had in ConfigureServices(IServiceCollection services) to the RegisterationMethod you previously created, in this way you're using the same services collection that ASP.NET using.

是的,做到的方式。这是来自github的示例.com / aspnet / logging存储库

Yes, that's the way to do it. Here is an example from the github.com/aspnet/logging repository:

public static IServiceCollection AddLogging(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
    services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));

    return services;
}



根据您的评论...



...听起来您正在尝试避免使用 合成根 。合成根是我们在依赖项注入容器中注册依赖项的单个位置。合成根目录放置在尽可能靠近应用程序入口点的位置(例如 ConfigureServices 方法),并且它属于应用程序而不是其库中。

Based on your comments...

...it sounds like you are trying to avoid having a composition root in your application. The composition root is the single location where we register dependencies with the dependency injection container. The composition root is placed as close as possible to the application's entry point (the ConfigureServices method, for instance) and it belongs in the application not in its libraries.