这篇博文主要关于ASP.NET SignalR & MVC 的依赖注入.
以下是在使用前需要查看的关于Autofac的文档, 博文内会说明如何实现.
Dependency Injection in SignalR: this
Dependency Injection in Middleware for ASP.NET OWIN: this
Set the Dependency Resolver for ASP.NET SignalR: this
Set the Dependency Resolver for ASP.NET MVC: this
说明
由于SignalR使用了中间件, 所以需要查看Autofac关于owin的文档.
需要引用的Autofac包:
<package id="Autofac" version="3.5.0" targetFramework="net45" />
<package id="Autofac.Mvc5" version="3.3.4" targetFramework="net45" />
<package id="Autofac.Owin" version="4.0.0" targetFramework="net45" />
<package id="Autofac.SignalR" version="3.0.2" targetFramework="net45" />
MVC实现
application_start():
protected void Application_Start() { var builder = new ContainerBuilder(); var container = builder.Build(); // register IModel
builder.RegisterType<Model>().As<IModel>();
builder.Update(container); // for mvc DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(container)); // for signalR GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container); }
IModel & Model:
public interface IModel { string Name { get; } } public class Model : IModel { public string Name => "this is MODEL."; }
接下来在控制器中使用已注入的IModel:
ModelController:
public class ModelController : Controller { private readonly IModel _model; public ModelController(IModel model) { _model = model; } public ActionResult Name() { return Json(_model.Name); } }
结果:
SignalR实现
ModelHub:
当有新的客户端成功连接后, 系统会将Model.Name响应给客户端.
public class ModelHub : Hub { private readonly IModel _model; public ModelHub(IModel model) { _model = model; } public override Task OnConnected() { Clients.Caller.broadcast(_model.Name); return base.OnConnected(); } }
结果:
注意:
如果发现 GlobalHost.ConnectionManager.GetHubContext<ConsoleHub>().Clients.All.boardcast() 方法无效, 则将HubConfiguration中的Resolver去掉即可.
HubConfiguration config = new HubConfiguration(); config.EnableJavaScriptProxies = true; //You should remove your dependency resolver code from here to Global.asax Application_Start method. Before setting the MVC properties. //config.Resolver = new SignalrDefaultDependencyResolver(UnityConfig.Container); // your dependency resolver //
解决方案来源: Call method from outside hub using GlobalHost.ConnectionManager.GetHubContext doesn't work