And*_*nov 6 c# simple-injector asp.net-core
我有一个AuthenticationHandler<>
依赖于应用程序服务的自定义实现。有没有办法解决AuthenticationHandler
简单注入器的依赖关系?或者也许是跨线注册,以便可以从 解析应用程序服务IServiceCollection
?
为简单起见,示例实现如下所示:
public class AuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly ITokenDecryptor tokenDecryptor;
public SecurityTokenAuthHandler(ITokenDecryptor tokenDecryptor,
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) :
base(options, logger, encoder, clock) =>
this.tokenDecryptor = tokenDecryptor;
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() =>
return tokenDecryptor.Decrypt(this);
}
...
services.AddAuthentication("Scheme")
.AddScheme<AuthenticationSchemeOptions, AuthHandler>("Scheme", options => { });
Run Code Online (Sandbox Code Playgroud)
目前的解决方案是手动跨线应用服务,不太方便:
services.AddTransient(provider => container.GetInstance<ITokenDecryptor>());
Run Code Online (Sandbox Code Playgroud)
涛的回答是对的。实现这一点的最简单方法是将交叉连接到简单注入器AuthHandler
。
这可以按如下方式完成:
// Your original configuration:
services.AddAuthentication("Scheme")
.AddScheme<AuthenticationSchemeOptions, AuthHandler>("Scheme", options => { });
// Cross wire AuthHandler; let Simple Injector create AuthHandler.
// Note: this must be done after the call to AddScheme. Otherwise it will
// be overridden by ASP.NET.
services.AddTransient(c => container.GetInstance<AuthHandler>());
// Register the handler with its dependencies (in your case ITokenDecryptor) with
// Simple Injector
container.Register<AuthHandler>();
container.Register<ITokenDecryptor, MyAwesomeTokenDecryptor>(Lifestyle.Singleton);
Run Code Online (Sandbox Code Playgroud)