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

查看:27
本文介绍了通过 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 中.但是,我希望能够在启动已经执行后执行此操作.有谁知道这是否可能?

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天全站免登陆