在运行时以编程方式添加/删除服务

时间:2019-09-19 12:52:01

标签: c# .net-core

据我所能做的就是通过IServiceCollection添加新服务

是否可以在运行时添加和删除这些服务?

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyService, MyService>();

    var serviceProvider = services.BuildServiceProvider();
    var service = serviceProvider.GetService<IMyService>();

AzureMultiTenantServiceBuilders.Build(services);
}

我试图弄清楚如何在运行时为我们的租户配置其他AzureAd,而不必重新启动系统。

public static class AzureMultiTenantServiceBuilders
{

    public static void Build(IServiceCollection services)
    {

        foreach (var tenant in Tenant.GetAll())
        {
            services.AddAuthentication()
                .AddAzureADTenanted(options =>
                {
                    options.ClientId = tenant.ClientId;
                    options.TenantId = tenant.TenantId;
                    options.Instance = "https://login.microsoftonline.com";
                });
        }

我发现这个Installing a new middleware at runtime in ASP.Net Core与添加中间件非常接近,但是我想做的是在运行时添加服务,所以这无济于事。

public static class RuntimeMiddlewareExtensions
{
    public static IServiceCollection AddRuntimeMiddleware(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton)
    {
         services.Add(new ServiceDescriptor(typeof(RuntimeMiddlewareService), typeof(RuntimeMiddlewareService), lifetime));

        AzureMultiTenantServiceBuilders.Build(services);
        return services;
    }

    public static IApplicationBuilder UseRuntimeMiddleware(this IApplicationBuilder app, Action<IApplicationBuilder> defaultAction = null)
    {
        var service = app.ApplicationServices.GetRequiredService<RuntimeMiddlewareService>();
        service.Use(app);
        if (defaultAction != null)
        {
            service.Configure(defaultAction);
        }
        return app;
    }
}

0 个答案:

没有答案