Alg*_*das 5 .net c# constructor dependency-injection .net-core
我有一个AuthenticationStrategy类,我将在控制器构造函数中注入.
我有两个IAuthenticationProviders:InternalAuthenticationProvider和ExternalAuthenticationProvider.
在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)
有任何想法吗?
一种选择是使 AuthenticationStrategy 通用。那么你可能会因类型而异
config.Scan(assembly =>
{
assembly.AssemblyContainingType(typeof(AuthenticationProvider));
assembly.ConnectImplementationsToTypesClosing(typeof(IAuthenticationProvider<>));
});
Run Code Online (Sandbox Code Playgroud)
上面的代码会扫描 dll,因此您也不必注册每一个 dll。
| 归档时间: |
|
| 查看次数: |
2845 次 |
| 最近记录: |