有陣子沒更新這個系列了,最近太忙了。本篇帶來的是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); } }
看一下最終的效果:
轉載請注明出處:http://www.companysz.com/royding/p/3875915.html
新聞熱點
疑難解答