Wiring SignalR with Autofac

Tags: autofac, signalr, english

After having a bit of struggle recently (which was quite fun, btw) with making two cool software pieces – Orchard and SignalR – work together, I came up with a simple library that allows you to wire SignalR’s internal dependency injection mechanism with Autofac. Useful thing if you already use Autofac and wish to keep all the dependencies there.

Orchard uses Autofac, so it was pretty obvious that something like this would be necessary at some point to make everything work.

The code is available at GitHub: https://github.com/pszmyd/SignalR.Autofac. I’ll publish the lib as NuGet package shortly.

Usage

It’s simple as hell – just a single class. To use it in your ASP.NET app, you need to set the SignalR resolver to AutofacDependencyResolver in your bootstrapping/initialization code:

var resolver = new AutofacDependencyResolver(lifetimeScope); 
AspNetHost.SetResolver(resolver); 

It takes a single ctor argument – your Autofac container instance (ILifetimeScope).

The simplest example could look like this (assuming Initialize is a method that bootstraps your application):

public void Initialize() { 
    // Building the Autofac container 
    var builder = new ContainerBuilder(); 
    builder.RegisterType<SomeType>().As<ISomeInterface>; 
    
    // .... 

    var container = builder.Build(); 
    var resolver = new AutofacDependencyResolver(container); 
    AspNetHost.SetResolver(resolver); 
}

And that’s all. Now, you can use all the types that SignalR registers (eg. IConnectionManager) in other parts of your application and vice-versa.

blog comments powered by Disqus