我刚开始在MVC 4项目中探索SignalR。我想做的其中一件事是将Ninject DI添加到我们的Hub类中。两个问题:
1)我找到并安装了SignalR.Ninject,但是这样做了,我不太清楚我用它做了什么。我尝试将以下行添加到AppStart NinjectWebCommon文件中的RegisterServices()方法,但这会产生编译错误。
private static void RegisterServices(IKernel kernel)
{
kernel.Load(
new Repositories.AssetModule()
);
GlobalHost.DependencyResolver = new
SignalR.Ninject.NinjectDependencyResolver(kernel);
}
2)一旦正确配置,我可以使用Hub类的构造函数注入,还是需要使用属性注入和[Inject]属性?
任何方向都会非常感激。
答案 0 :(得分:7)
我也一直在努力解决编译错误:
GlobalHost.DependencyResolver = new
SignalR.Ninject.NinjectDependencyResolver(kernel);
但是,我设法通过将NinjectDependencyResolver的内容复制到一个新类来解决它:
public class NinjectSignalRDependencyResolver : DefaultDependencyResolver
{
private readonly IKernel _kernel;
public NinjectSignalRDependencyResolver(IKernel kernel)
{
if (kernel == null)
{
throw new ArgumentNullException("kernel");
}
_kernel = kernel;
}
public override object GetService(Type serviceType)
{
return _kernel.TryGet(serviceType) ?? base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.GetAll(serviceType).Concat(base.GetServices(serviceType));
}
}
然后我在NinjectWebCommon类(由SignalR nuget提供)中的RegisterServices方法中设置解析器,如下所示:
private static void RegisterServices(IKernel kernel)
{
RouteTable.Routes.MapHubs(new NinjectSignalRDependencyResolver(kernel));
}
答案 1 :(得分:0)
我关注了@ TobiasNilsson的回答,但我收到了这个错误:无法从'SignalR.NinjectSignalRDependencyResolver'转换为'Microsoft.AspNet.SignalR.HubConfiguration
private static void RegisterServices(IKernel kernel)
{
GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(kernel);
}
然后其他地方:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHubs();//SignalR
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}