![](/img/trans.png)
[英]Changing whether a service is injected as scoped or transient via the .Net Core DI container at runtime?
[英]Register Service at Runtime via DI?
我正在使用 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();
}
}
在 Autofac 中可能有这样的事情:
private ILifetimeScope BeginChildScope()
{
return _lifetimeScope.BeginLifetimeScope(x =>
{
x.Register<IAuthenticationService>(b => new AuthenticationService());
});
}
using (var childScope = BeginChildScope())
{
// Do sth here
}
对于 .NET Core,我认为这是唯一可能的解决方案 atm.: Best strategy for creating a child container (or isolated scope) with Microsoft.Extensions.DependencyInjection
Microsoft 在此处声明 ASP.NET Core DI 不受支持的功能: https://learn.microsoft.com/en-us/do.net/core/extensions/dependency-injection-guidelines#default-service-container-replacement
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.