1. 程式人生 > 其它 >SignalR 循序漸進(四) Hub的生命週期以及IoC

SignalR 循序漸進(四) Hub的生命週期以及IoC

有陣子沒更新這個系列了,最近太忙了。本篇帶來的是Hub的生命週期以及IoC。

首先,Hub的生命週期,我們用一個Demo來看看:

public class TestHub : Hub
    {
        public TestHub()
        {
            Console.WriteLine(Guid.NewGuid().ToString());
        }

        public void Hello() { }
    }
static HubConnection hubConnection;
        static IHubProxy hubProxy;
        static List<IDisposable> clientHandlers = new List<IDisposable>();

        static void Main(string[] args)
        {
            hubConnection = new HubConnection("http://127.0.0.1:10086/");
            hubProxy = hubConnection.CreateHubProxy("TestHub");

            hubConnection.Start().ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    Console.WriteLine(t.Exception.Message);
                }
                else
                {
                    Console.WriteLine("Connectioned");
                }
            }).Wait();

            while (true)
            {
                hubProxy.Invoke("Hello");
                Thread.Sleep(1000);
            }
        }

給測試Hub增加建構函式,在裡面輸出一個Guid。然後客戶端呼叫一個空的Hello方法。我們來看看實際執行情況:

可以看到,客戶端每請求一次服務端,都會建立一個新的Hub例項來進行操作。

好,這是基本的應用場景。如果Hub裡有一些需要持久的東西,比如一個訪問計數器,我們把Hub改一下:

public class TestHub : Hub
    {
        int count;

        public TestHub()
        {
            Console.WriteLine(Guid.NewGuid().ToString());
        }

        public void Hello()
        {
            count++;
            Console.WriteLine(count);
        }
    }

這時候要怎麼辦呢?這時候就需要對Hub進行例項管理。在Startup裡可以通過Ioc的方式將Hub的例項進行注入:

public class Startup
    {
        TestHub testHub = new TestHub();

        public void Configuration(IAppBuilder app)
        {
            GlobalHost.DependencyResolver.Register(typeof(TestHub), () => testHub);

            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableDetailedErrors = true,
                    EnableJSONP = true
                };
                map.RunSignalR(hubConfiguration);
            });
        }
    }

這樣改造後,我們再來看看實際執行情況:

好,目前來說一切都ok,我們能通過全域性註冊例項。現在有一個這樣的需求,TestHub的建構函式需要注入一個倉儲介面,例如:

public class TestHub : Hub
    {
        int count;

        public TestHub(IRepository repository)
        {
            this.repository = repository;
        }

        IRepository repository;

        public void Hello()
        {
            count++;
            repository.Save(count);
        }
    }

這樣改完以後,勢必需要在Startup裡也做改動:

public class Startup
    {
        public Startup(IRepository repository)
        {
            testHub = new TestHub(repository);
        }

        TestHub testHub;

        public void Configuration(IAppBuilder app)
        {
            GlobalHost.DependencyResolver.Register(typeof(TestHub), () => testHub);

            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableDetailedErrors = true,
                    EnableJSONP = true
                };
                map.RunSignalR(hubConfiguration);
            });
        }
    }

好,到這步位置,一切都在掌控之中,只要我們在入口的地方用自己熟悉的IoC元件把例項注入進來就ok了,如圖:

WebApp.Start完全沒有地方給予依賴注入,這條路走不通,看來得另尋方法。

Owin提供了第二種方式來啟動,通過服務工廠來解決IoC的問題,而且是原生支援:

static void Main(string[] args)
        {
            var url = "http://*:10086/";
            var serviceProviders = (ServiceProvider)ServicesFactory.Create();
            var startOptions = new StartOptions(url);
            serviceProviders.Add<IRepository, Repository>();
            var hostingStarter = serviceProviders.GetService<IHostingStarter>();

            hostingStarter.Start(startOptions);
            Console.WriteLine("Server running on {0}", url);
            Console.ReadLine();
        }

我們將輸出計數的位置挪到倉儲例項裡:

public class Repository : IRepository
    {
        public void Save(int count)
        {
            Console.WriteLine(count);
        }
    }

看一下最終的效果: