C#.Net核心依赖注入,为构造函数注入多个参数

Alg*_*das 5 .net c# constructor dependency-injection .net-core

我有一个AuthenticationStrategy类,我将在控制器构造函数中注入.

我有两个IAuthenticationProviders:InternalAuthenticationProviderExternalAuthenticationProvider.
AuthenticationStrategy构造函数中,我想注入所有提供者.
示例代码:

public class AuthenticationStrategy
{
    private readonly Dictionary<string, IAuthenticationProvider> _authenticationProviders;

    public AuthenticationStrategy(IAuthenticationProvider[] authenticationProviders)
    {
        if (authenticationProviders == null)
        {
            throw new ArgumentNullException("AuthenticationProviders");
        }

        _authenticationProviders = authenticationProviders
            .ToDictionary(x => nameof(x), x => x);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用依赖注入注入多个提供程序?示例代码:

services.AddScoped<IAuthenticationProvider, InternalAuthenticationProvider>();
services.AddScoped<IAuthenticationProvider, ExternalAuthenticationProvider>();
services.AddScoped<AuthenticationStrategy>();
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Tho*_*lle 1

一种选择是使 AuthenticationStrategy 通用。那么你可能会因类型而异

config.Scan(assembly =>
{
    assembly.AssemblyContainingType(typeof(AuthenticationProvider));
    assembly.ConnectImplementationsToTypesClosing(typeof(IAuthenticationProvider<>));
});
Run Code Online (Sandbox Code Playgroud)

上面的代码会扫描 dll,因此您也不必注册每一个 dll。