通过DI在运行时注册服务?

编程入门 行业动态 更新时间:2024-10-26 17:24:35
本文介绍了通过DI在运行时注册服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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在运行时注册服务?

本文发布于:2023-11-17 11:39:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609892.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!