我正在使用ASP.NET Core,并希望在运行时将服务添加到IServiceProvider,因此可以通过DI在整个应用程序中使用它。
I am using ASP.NET Core and want to add a service to the IServiceProvider at runtime, so it can be used across the application via DI.
例如,一个简单的示例就是用户转到设置控制器并将身份验证设置从打开更改为关闭。在那种情况下,我想替换在运行时注册的服务。
For instance, a simple example would be that the user goes to the settings controller and changes an authentication setting from "On" to "Off". In that instance I would like to replace the service that was registered at runtime.
设置控制器中的伪代码:
Psuedo Code in the Settings 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执行后执行此操作。有人知道这是否有可能吗?
This logic works fine when I am doing it in my Startup.cs because the IServiceCollection has not been built into a IServiceProvider. However, I want to be able to do this after the Startup has already executed. Does anyone know if this is even possible?
推荐答案我将创建一个在运行时决定正确服务的服务工厂,而不是在运行时注册/删除服务。
Instead of registering/removing service at runtime, i would create a service factory which decides right service at runtime.
services.AddTransient<AuthenticationService>(); services.AddTransient<NoAuthService>(); services.AddTransient<IAuthenticationServiceFactory, AuthenticationServiceFactory>();AuthenticationServiceFactory.cs
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(); } }更多推荐
通过DI在运行时注册服务?
发布评论