我正在使用 ASP.NET Core 并希望在运行时向 IServiceProvider 添加一个服务,以便它可以通过 DI 在整个应用程序中使用。
例如,一个简单的示例是用户转到设置 Controller 并将身份验证设置从“打开”更改为“关闭”。在那种情况下,我想替换在运行时注册的服务。
设置 Controller 中的伪代码:
if(settings.Authentication == false)
{
services.Remove(ServiceDescriptor.Transient<IAuthenticationService, AuthenticationService>());
services.Add(ServiceDescriptor.Transient<IAuthenticationService, NoAuthService>());
}
else
{
services.Remove(ServiceDescriptor.Transient<IAuthenticationService, NoAuthService>
services.Add(ServiceDescriptor.Transient<IAuthenticationService, AuthenticationService>());
}
当我在 Startup.cs 中执行此逻辑时,此逻辑工作正常,因为 IServiceCollection 尚未内置到 IServiceProvider 中。但是,我希望能够在 Startup 已经执行之后执行此操作。有谁知道这是否可能?
最佳答案
我不会在运行时注册/删除服务,而是创建一个在运行时决定正确服务的服务工厂。
services.AddTransient<AuthenticationService>();
services.AddTransient<NoAuthService>();
services.AddTransient<IAuthenticationServiceFactory, AuthenticationServiceFactory>();
AuthenticationServiceFactory.cs
public class AuthenticationServiceFactory: IAuthenticationServiceFactory
{
private readonly AuthenticationService _authenticationService;
private readonly NoAuthService_noAuthService;
public AuthenticationServiceFactory(AuthenticationService authenticationService, NoAuthService noAuthService)
{
_noAuthService = noAuthService;
_authenticationService = authenticationService;
}
public IAuthenticationService GetAuthenticationService()
{
if(settings.Authentication == false)
{
return _noAuthService;
}
else
{
return _authenticationService;
}
}
}
类中的用法:
public class SomeClass
{
public SomeClass(IAuthenticationServiceFactory _authenticationServiceFactory)
{
var authenticationService = _authenticationServiceFactory.GetAuthenticationService();
}
}
关于c# - 通过 DI 在运行时注册服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40654801/