通过DI在运行时注册服务? [英] Register Service at Runtime via DI?

查看:62
本文介绍了通过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在运行时注册服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆