有陣子沒更新這個系列了,最近太忙了。本篇帶來的是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方法。我們來看看實際運行情況:
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);
});
}
}
這樣改造後,我們再來看看實際運行情況:
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了,如圖:
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.cnblogs.com/royding/p/3875915.html