替换.net核心

时间:2017-01-11 18:21:33

标签: c# .net dependency-injection asp.net-core

好的,所以我在运行时期间将一个类实例添加到startup.cs中的服务集合中,如下所示:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<WidgetProvider, BlueWidgetProvider>();
    }

但是,在运行时,我希望应用程序能够用BlueWidgetProvider替换RedWidgetProvider。我该怎么做呢?我知道您可以在Remove上使用IServicesCollection方法,但我如何将其公开给我的应用程序?我可以公开添加IServiceProvider的{​​{1}},如下所示,但我不确定如何访问底层服务集合。

WidgetProvider

1 个答案:

答案 0 :(得分:1)

对我来说,一种方法是取消host.Run方法,然后再次递归调用Main

进行一些设置更改,告知启动在配置服务时使用其他窗口小部件提供程序:

public void UseRedWidgetProvider() {
    database.UseRedWidgetProvider();
    Restart();
}

取消host.Run方法的方法:

public void Restart() 
{
    Current.AppCancellationSource.Cancel();
}

包含取消令牌的静态类:

public static class Current 
{
    public static CancellationTokenSource AppCancellationSource = new CancellationTokenSource();
}

在调用取消令牌后递归启动Main

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    CoreCurrent.Protector = ActivatorUtilities.CreateInstance<DataProtect>(host.Services);

    Current.Services = host.Services;

    Current.SetDbConfigurationState();

    host.Run(Current.AppCancellationSource.Token);

    //reset token and call main again
    host.Dispose();
    Current.AppCancellationSource = new System.Threading.CancellationTokenSource();
    Main(args);
}

这似乎对我有用。一旦我调用取消令牌,应用程序似乎很快就会重新启动,现在使用了新的小部件提供程序。不完全确定这是一个好的做法,还是有任何组件可能搞砸了。