且构网

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

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

更新时间:2022-01-10 05:55:42

...在 ASP.NET 核心项目 [s] 中,我们有 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:

将你的复合根放在你的应用程序中,尽可能靠近入口点.

假设您有一个引用多个类库的应用程序.在应用程序的 Startup 类中,使用 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.

好的,将您在 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.

是的,这就是这样做的方式.这是 .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;
}

根据您的评论...

...听起来您正试图避免使用 组合root 在您的应用程序中.组合根是我们向依赖注入容器注册依赖的单一位置.组合根尽可能靠近应用程序的入口点(例如,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.