手动初始化具有Dependence Injected参数的单例

时间:2016-04-07 15:34:47

标签: c# .net dependency-injection singleton

我的环境是,Asp.net5,MVC6。我想定期使用SingalR向客户端广播一些服务器端信息。我创造了一个" Braodcaster"像这样,

public class ServerInfoHub : Hub
{

}

public class Broadcaster
{
    private readonly Timer looper;
    private readonly IHubContext hubContext;
    private readonly PerformanceCounter cpuCounter;
    private readonly PerformanceCounter ramCounter;
    private static Broadcaster instance;

    public Broadcaster(IHubContext hubContext)
    {
        this.hubContext = hubContext;
        cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        ramCounter = new PerformanceCounter("Memory", "Available MBytes");
        looper = new Timer(new TimerCallback(onTimer), this, TimeSpan.Zero, TimeSpan.FromSeconds(2));
    }

    private void onTimer(object target)
    {
        hubContext.Clients.All.broadcastMessage(ramCounter.NextValue(), cpuCounter.NextValue());
    }
}

在Startup.cs中将其作为单身人士(" Broadcaster")

        public void ConfigureServices(IServiceCollection services)
    {
        //ignored unrelated code
        services.AddSingleton(_ => new Broadcaster(GlobalHost.ConnectionManager.GetHubContext<ServerInfoHub>()));
    }

虽然,我想要这个&#34; Broadcaster&#34;在应用程序启动时初始化。而且,&#34; Broadcaster&#34;没有其他依赖它的模块,&#34; Braodcaster&#34;取决于&#34; IHubContext&#34;,这意味着我可能无法创建静态的&#39; CreateInstance&#39; &#39; Broadcaster&#39;中的方法并在Startup.cs中直接调用它,就像这样

public class Broadcaster
{
 private static Broadcaster instance;


    public static void CreateInstance()
    {
        if(instance == null)
        {
            instance = new Broadcaster(???);
        }
    }

    private Broadcaster(IHubContext hubContext) {}
}

我怎样才能实现它?

0 个答案:

没有答案