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

标签 c# asp.net-core asp.net-core-mvc .net-core

我正在使用 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();
    }
}

关于c# - 通过 DI 在运行时注册服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40654801/

相关文章:

c# - 在 C# 中,改进单元测试反馈循环的好方法是什么?

c# - C# 编译器是否计算常数的数学?

c# - 如何在 .NET Core 中使用 HttpWebResponse 和 WebResponse?

c# - 该项目使用 Microsoft.NETCore.App 版本 2.1.0 恢复,但使用当前设置,将使用版本 2.1.0-rtm-26515-03

javascript - 编写body元素以包含css类时如何访问浏览器本地存储

asp.net-core-mvc - 支持多个同类型的AuthenticationSchemes

c# - 无法将对象...转换为类型

asp.net-core - 启动期间通过 Config.MapRoute 创建的路由的 Swashbuckle-Swagger 文档?

c# - 为什么异常重定向到不同的页面?

c# - 有没有办法在 C# 中做这样的事情?