A.F*_*Fry 4 c# asp.net-core-mvc .net-core asp.net-core
我正在使用ASP.NET Core并希望在运行时向IServiceProvider添加服务,因此可以通过DI在整个应用程序中使用它.
例如,一个简单的例子是用户进入设置控制器并将认证设置从"开"更改为"关".在那个例子中,我想替换在运行时注册的服务.
设置控制器中的Psuedo代码:
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>());
}
Run Code Online (Sandbox Code Playgroud)
当我在Startup.cs中执行此操作时,此逻辑工作正常,因为IServiceCollection尚未构建到IServiceProvider中.但是,我希望能够在启动已经执行之后执行此操作.有谁知道这是否可能?
我不是在运行时注册/删除服务,而是创建一个服务工厂,它在运行时决定正确的服务.
services.AddTransient<AuthenticationService>();
services.AddTransient<NoAuthService>();
services.AddTransient<IAuthenticationServiceFactory, AuthenticationServiceFactory>();
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在课堂上使用:
public class SomeClass
{
public SomeClass(IAuthenticationServiceFactory _authenticationServiceFactory)
{
var authenticationService = _authenticationServiceFactory.GetAuthenticationService();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2358 次 |
| 最近记录: |