简体   繁体   English

.NET 具有不同服务实现的库中的核心依赖注入

[英].NET Core Dependency Injection in library with different service implementation

I have a library that configures dependency injection for another library (via IServiceCollection extension).我有一个库为另一个库配置依赖注入(通过IServiceCollection扩展)。 However, that other library requires a different implementation of a service that is already registered in the application that will be using it even though only one implementation of that service is expected in the application.但是,该其他库需要已在将使用它的应用程序中注册的服务的不同实现,即使在应用程序中只期望该服务的一个实现。

Ie, Application relies on Service A with implementation A1 and Service B (from a separate library) that relies on Service A with implementation A2.即,应用程序依赖于具有实现 A1 的服务 A,而服务 B(来自单独的库)依赖于具有实现 A2 的服务 A。 Both implementations A1 and A2 come from libraries and are internal (registered using library-specific IServiceCollection extensions).实现 A1 和 A2 都来自库并且是internal的(使用库特定的IServiceCollection扩展注册)。

What is the way to make this work without exposing internal classes or changing the service implementation used by the application?在不公开internal类或更改应用程序使用的服务实现的情况下,有什么方法可以使这项工作正常进行?

Register the service in the library that you have access to as a concrete type.在您有权访问的库中将服务注册为具体类型。

So that the services are registered like this:这样就可以像这样注册服务:

services.AddTransient<ServiceA>();
services.AddTransient<IService, ServiceB>();

Then just refer to them like this:然后像这样引用它们:

public class ClassThatNeedsServiceA
{
    private ServiceA _serviceA;
    
    public ClassThatNeedsServiceA(ServiceA serviceA)
    {
        _serviceA = serviceA;
    }
}

public class ClassThatNeedsServiceB
{
    private ServiceB _serviceB;
    
    public ClassThatNeedsServiceA(IService serviceB)
    {
        _serviceB = serviceB;
    }
}

This will allow both services to be accessed correctly where needed.这将允许在需要时正确访问这两种服务。

If the new library needs to expose access to ServiceA and or ServiceB externally then it might be an indication that they should not be internal.如果新库需要在外部公开对ServiceA和/或ServiceB的访问权限,则可能表明它们不应该是内部的。

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

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