I have been playing around w/ SignalR and I have to say IT IS PRETTY COOL. I have been pretty impressed with the simplicity and the ease of the the framework as well as its extension points. One area that I am happy to see the ability to use IoC within SignalR, more so the ability to use any container I want to handle the DI.
Recently I switched to using Autofac (for no other reason to learn something different). Because I am learning this I of course wanted to use this in SignalR, and of course it was pretty simple.
To use Autofac w/ SignalR we need to do the following
- Add Autofac to your project. (using Nuget: Install-Package Autofac)
- Add Autofac.Configuration to the project, this allows for convention based bindings (using Nuget: Install-Package Autofac.Configuration)
- Add Autofac.SignalR to the project (using Nuget: Install-Package autofac.signalr)
- Setup the bindings for Autofac (see below)
- Set the Autofac resolver for SignalR
Setup the Bindings for Autofax
The first thing we need to do is create the general wiring for Autofax. The last 2 lines are the magic to get SignalR to use Autofac. Here we are creating the correct resolver class and setting it as the global DependencyResolver
var builder = new ContainerBuilder();
var service = builder.Build();
var resolver = new AutofacDependencyResolver(service);
GlobalHost.DependencyResolver = resolver;
Below is the code for my Autofac module. Please make sure you add the .AsSelf convention. If you do NOT do this your hubs will not be created. This is because there is no interface attached so Autofac will have no idea how to create the class.
public class ServerIoCModule : Module
protected override void Load(ContainerBuilder builder)
var thisAssembly = typeof(ServerIoCModule).Assembly;
Once you have the above setup correctly you will be able to inject dependencies into your Hub as well as have your Hubs created via IoC
Till Next Time,
11-27-2013 7:31 AM