Using SignalR.Ninject with ASP.NET MVC3 and the Ninject.MVC3 Nuget Package

Today I updated SignalR to version 0.4.0 and decided to include the SignalR.Ninject project into my ASP.NET MVC3 application as well. As written on the SignalR github page (https://github.com/SignalR/SignalR/wiki/Extensibility), SignalR is built with dependency injection in mind, and besides allowing one to replace most of the SignalR pieces, SignalR also allows one to replace the IDependencyResolver.

This blog post demonstrates how to replace the standard dependency resolver used in SignalR with the Ninject dependency resolver implementation for SignalR (https://github.com/SignalR/SignalR.Ninject).

First of all, I decided to replace the dependency resolver because I’m already using Ninject for dependency injection in my controllers and my custom membership- and role providers as well. So, by using the same dependency resolver with SignalR too, I’m able to use Ninject for inversion of control in my entire ASP.NET MVC3 application.

To replace the dependency resolver in SignalR with Ninject, follow these steps:

1. Open App_Start\NinjectMVC3.cs (I’m using the Ninject.MVC3 NuGet package (http://nuget.org/packages/Ninject.MVC3) v.2.2.2.0)

2. In the RegisterServices(IKernel kernel) method register the SignalR.Ninject.NinjectDependencyResolver with SignalR.Hosting.AspNet.AspNetHost using the available local instance of the IKernel:

private static void RegisterServices(IKernel kernel)
{
    ...
    kernel.Bind<IUserService>().To<UserService>();
    SignalR.Hosting.AspNet.AspNetHost.SetResolver(new SignalR.Ninject.NinjectDependencyResolver(kernel));
}

3. In my Hub, I am using a property injected instance of IUserService, so I added the Ninject [Inject] annotation like this:

public class MyHub: Hub, IDisconnect
{
    [Inject]
    public IUserService UserService { get; set; }
    ...

4. Build, test, donez! 🙂

Courtesy: https://github.com/SignalR/SignalR/wiki/Extensibility

SignalR source and NuGet packages

SignalR @GitHub: https://github.com/SignalR/SignalR

SignalR NuGet Pkg.: http://nuget.org/packages/SignalR

SignalR.Ninject NuGet Pkg.: http://nuget.org/packages/SignalR.Ninject

Tags: , , ,

2 Responses to “Using SignalR.Ninject with ASP.NET MVC3 and the Ninject.MVC3 Nuget Package”

  1. guo April 25, 2012 at 2:03 am #

    great post.

  2. Priscilla Decker July 16, 2013 at 6:07 am #

    You can check out the default dependency resolver at GitHub . You can find all the services that are registered – the resolver keeps then in a private readonly dictionary Dictionary<Type, IList<Func<object>>>. If you fancy replacing an internal part of SignalR with your own implementation, you can locate the correct interface and register your own implementation in your container. The custom dependency resolver will then resolve your implementation.

Leave a Reply