2
votes

I am just beginning to explore SignalR in our MVC 4 project. One of the things I would like to do is add Ninject DI to our Hub classes. Two questions:

1) I found and installed SignalR.Ninject, but having done so, I'm not quite sure what I do with it. I tried add the following line to the RegisterServices() method in the AppStart NinjectWebCommon file, but this produced a compilation error.

private static void RegisterServices(IKernel kernel)
{
    kernel.Load(
        new Repositories.AssetModule()
    );

    GlobalHost.DependencyResolver = new
        SignalR.Ninject.NinjectDependencyResolver(kernel);
}

2) Once correctly configured, can I use constructor injection with the Hub class, or do I need to use property injection with the [Inject] attribute?

Any direction would be much appreciated.

2
Having same problem hereanthonypliu

2 Answers

7
votes

I too have struggled with the compilation error on:

GlobalHost.DependencyResolver = new
        SignalR.Ninject.NinjectDependencyResolver(kernel);

However, I managed to solve it by copying the contents of NinjectDependencyResolver to a new class:

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));
        }
    }

Then I set the resolver in the method RegisterServices in class NinjectWebCommon (provided by SignalR nuget) like this:

private static void RegisterServices(IKernel kernel)
{            
   RouteTable.Routes.MapHubs(new NinjectSignalRDependencyResolver(kernel));
}
0
votes

I followed @TobiasNilsson's answer, but I was getting this error: cannot convert from 'SignalR.NinjectSignalRDependencyResolver' to 'Microsoft.AspNet.SignalR.HubConfiguration

private static void RegisterServices(IKernel kernel)
{
    GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(kernel);
}       

then else where:

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 }
    );
}