SignalR with an IoC container


There seem to be a number of posts out there on how to use an SignalR with an IoC container e.g. MS Unity. Nearly all of them of them seem to be taking a sledgehammer approach to solve what most people generally want to do, which is create their Hubs with an IoC container. They generally don’t want to replace all of SignalR’s internal dependencies.

The easiest way to get dependencies injected into SignalR hubs is not by creating your own DefaultDependencyResolver – doing that will hand over control to you for creating not just Hubs, but basically all the different components within the SignalR pipeline. Worse still, for an IoC container like Unity which can create concretes that have not explicitly been registered, it can make life much more complicated.

A simpler approach is simply to register an implementation of the IHubActivator, as below: –

/// <summary>
/// Uses Unity to create Hubs - and ONLY Hubs.
/// </summary>
// Register with GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => unityHubActivator);
public class UnityHubActivator : IHubActivator
{
private readonly IUnityContainer container;
public UnityHubActivator(IUnityContainer container)
{
this.container = container;
}
public IHub Create(HubDescriptor descriptor)
{
return (IHub)container.Resolve(descriptor.HubType);
}
}
public class ExampleHub : Hub
{
private readonly IMyService myService;
private readonly ILogger logger;
public ExampleHub(IMyService myService, ILogger logger)
{
this.myService = myService;
this.logger = logger;
}
// Blah blah....
}
view raw signalrIoc.cs hosted with ❤ by GitHub

The HubActivator will get called only when SignalR needs to create a Hub specifically; you hand control over to your IoC container to create it, along with any of its dependencies. Much easier than the other approach, and easier to reason about.

Leave a Reply