Using Simple Injector with SignalR

UPDATE This answer has been updated for SignalR version 1.0

This is how to build a SignalR IDependencyResolver for Simple Injector:

public sealed class SimpleInjectorResolver 
    : Microsoft.AspNet.SignalR.IDependencyResolver
{
    private Container container;
    private IServiceProvider provider;
    private DefaultDependencyResolver defaultResolver;

    public SimpleInjectorResolver(Container container)
    {
        this.container = container;
        this.provider = container;
        this.defaultResolver = new DefaultDependencyResolver();
    }

    [DebuggerStepThrough]
    public object GetService(Type serviceType)
    {
        // Force the creation of hub implementation to go
        // through Simple Injector without failing silently.
        if (!serviceType.IsAbstract && typeof(IHub).IsAssignableFrom(serviceType))
        {
            return this.container.GetInstance(serviceType);
        }

        return this.provider.GetService(serviceType) ?? 
            this.defaultResolver.GetService(serviceType);
    }

    [DebuggerStepThrough]
    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.container.GetAllInstances(serviceType);
    }

    public void Register(Type serviceType, IEnumerable<Func<object>> activators)
    {
        throw new NotSupportedException();
    }

    public void Register(Type serviceType, Func<object> activator)
    {
        throw new NotSupportedException();
    }

    public void Dispose()
    {
        this.defaultResolver.Dispose();
    }
}

Unfortunately, there is an issue with the design of the DefaultDependencyResolver. That's why the implementation above does not inherit from it, but wraps it. I created an issue about this on the SignalR site. You can read about it here. Although the designer agreed with me, unfortunately the issue hasn't been fixed in version 1.0.

I hope this helps.


Well, I tried yesterday and I've found a solution. According to me, the only moment where I want dependency injection in SignalR is for my hubs: I don't care about how SignalR is working inside ! So instead of replacing the DependencyResolver, I created my own implementation of IHubActivator :

public class SimpleInjectorHubActivator : IHubActivator
{
    private readonly Container _container;

    public SimpleInjectorHubActivator(Container container)
    {
        _container = container;
    }

    public IHub Create(HubDescriptor descriptor)
    {
        return (IHub)_container.GetInstance(descriptor.HubType);
    }
}

That I can register like this (in Application_Start) :

var activator = new SimpleInjectorHubActivator(container);
GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => activator);
RouteTable.Routes.MapHubs();

From SignalR 2.0 (and the beta's) there is a new way of setting the dependency resolver. SignalR moved to OWIN startup to do the configuration. With Simple Injector you'd do it like this:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HubConfiguration()
        {
            Resolver = new SignalRSimpleInjectorDependencyResolver(Container)
        };
        app.MapSignalR(config);
    }
}

public class SignalRSimpleInjectorDependencyResolver : DefaultDependencyResolver
{
    private readonly Container _container;
    public SignalRSimpleInjectorDependencyResolver(Container container)
    {
        _container = container;
    }
    public override object GetService(Type serviceType)
    {
        return ((IServiceProvider)_container).GetService(serviceType)
               ?? base.GetService(serviceType);
    }

    public override IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.GetAllInstances(serviceType)
            .Concat(base.GetServices(serviceType));
    }
}

You'd have to explicitly inject your hubs like so:

container.Register<MessageHub>(() => new MessageHub(new EFUnitOfWork()));

This config is running live on a high traffic website without problems.


Want to throw my 2 cents in here with the other answers, which can be helpful in finding your own way with dependency injection in SignalR, either using SimpleInjector or another IoC.

Using @Steven's answer

If you decide to use Steven's answer, make sure you register your hub routes before you compose the root. The SignalRRouteExtensions.MapHubs extension method (a.k.a. routes.MapHubs()) will call Register(Type, Func<object>) on the GlobalHost.DependencyResolver when mapping the hub routes, so if you swap out the DefaultDependencyResolver with Steven's SimpleInjectorResolver before the routes are mapped, you will run into his NotSupportedException.

Using @Nathanael Marchand's answer

This is my favorite. Why?

  1. Less code than the SimpleInjectorDependencyResolver.
  2. No need to replace the DefaultDependencyResolver (a.k.a. GlobalHost.DependencyResolver), which means even less code.
  3. You can compose the root either before or after mapping hub routes, since you are not replacing the DefaultDependencyResolver, it will "just work".

Like Nathanael said though, this is only if you care about the dependencies on your Hub classes, which will probably be the case for most. If you want to mess around with injecting other dependencies into SignalR, you might want to go with Steven's answer.

Problems with per-web-request dependencies in a Hub

There is an interesting thing about SignalR... when a client disconnects from a hub (for example by closing their browser window), it will create a new instance of the Hub class in order to invoke OnDisconnected(). When this happens, HttpContext.Current is null. So if this Hub has any dependencies that are registered per-web-request, something will probably go wrong.

In Ninject

I tried out SignalR dependency injection using Ninject and the ninject signalr dependency resolver on nuget. With this configuration, dependencies that are bound .InRequestScope() will be created transiently when injected into a Hub during a disconnect event. Since HttpContext.Current is null, I suppose Ninject just decides to ignore it and create transient instances without telling you. Maybe there was a configuration setting to tell ninject to warn about this, but it was not the default.

In SimpleInjector

SimpleInjector on the other hand will throw an exception when a Hub depends on an instance that is registered with WebRequestLifestlyle:

The registered delegate for type NameOfYourHub threw an exception. The registered delegate for type NameOfYourPerRequestDependency threw an exception. The YourProject.Namespace.NameOfYourPerRequestDependency is registered as 'PerWebRequest', but the instance is requested outside the context of a HttpContext (HttpContext.Current is null). Make sure instances using this lifestyle are not resolved during the application initialization phase and when running on a background thread. For resolving instances on background threads, try registering this instance as 'Per Lifetime Scope': https://simpleinjector.readthedocs.io/en/latest/lifetimes.html#scoped.

...note this exception will only bubble up when HttpContext.Current == null, which as far as I can tell, only happens when SignalR requests a Hub instance in order to invoke OnDisconnected().

Solutions for per-web-request dependencies in a Hub

Note that none of these are really ideal, it will all depend on your application requirements.

In Ninject

If you need non-transient dependencies, just don't override OnDisconnected() or do anything custom there with the class dependencies. If you do, each dependency in the graph will be a separate (transient) instance.

In SimpleInjector

You need a hybrid lifestyle between WebRequestLifestlye and either Lifestyle.Transient, Lifestyle.Singleton, or LifetimeScopeLifestyle. When HttpContext.Current is not null, dependencies will only live as long as the web request as you would normally expect. However when HttpContext.Current is null, dependencies will either be injected transiently, as singletons, or within a lifetime scope.

var lifestyle = Lifestyle.CreateHybrid(
    lifestyleSelector: () => HttpContext.Current != null,
    trueLifestyle: new WebRequestLifestyle(),
    falseLifestyle: Lifestyle.Transient // this is what ninject does
    //falseLifestyle: Lifestyle.Singleton
    //falseLifestyle: new LifetimeScopeLifestyle()
);

More about LifetimeScopeLifestyle

In my case, I have an EntityFramework DbContext dependency. These can be tricky because they can expose problems when registered transiently or as singletons. When registered transiently, you can end up with exceptions while trying to work with entities attached to 2 or more DbContext instances. When registered as a singleton, you end up with more general exceptions (don't ever register a DbContext as a singleton). In my case I needed the DbContext to live within a specific lifetime in which the same instance can be reused across many nested operations, which means I needed the LifetimeScopeLifestyle.

Now if you used the hybrid code above with the falseLifestyle: new LifetimeScopeLifestyle() line, you will get another exception when your custom IHubActivator.Create method executes:

The registered delegate for type NameOfYourHub threw an exception. The NameOfYourLifetimeScopeDependency is registered as 'LifetimeScope', but the instance is requested outside the context of a lifetime scope. Make sure you call container.BeginLifetimeScope() first.

The way you have set up a lifetime scoped dependency goes like this:

using (simpleInjectorContainer.BeginLifetimeScope())
{
    // resolve solve dependencies here
}

Any dependencies that are registered with lifetime scope must be resolved within this using block. Furthermore, if any of those dependencies implement IDisposable, they will be disposed of at the end of the using block. Don't be tempted to do something like this:

public IHub Create(HubDescriptor descriptor)
{
    if (HttpContext.Current == null)
        _container.BeginLifetimeScope();
    return _container.GetInstance(descriptor.HubType) as IHub;
}

I asked Steven (who also happens to be the SimpleInjector author in case you didn't know) about this, and he said:

Well.. If you don’t dispose the LifetimeScope, you’ll be in big trouble, so make sure they get disposed. If you don’t dispose the scopes, they will hang around for ever in ASP.NET. This is because scopes can be nested and reference their parent scope. So a thread keeps alive the most inner scope (with its cache) and this scope keeps alive its parent scope (with its cache) and so on. ASP.NET pools threads and doesn’t reset all values when it grabs a thread from the pool, so this means that all scopes stay alive and the next time you grab a thread from the pool and start a new lifetime scope, you will simply creating a new nested scope and this will keep stacking up. Sooner or later, you’ll get an OutOfMemoryException.

You can't use IHubActivator to scope the dependencies because it does not live as long as the Hub instance it creates. So even if you wrapped the BeginLifetimeScope() method in a using block, your dependencies would be disposed immediately after the Hub instance is created. What you really need here is another layer of indirection.

What I ended up with, with much thanks to Steven's help, is a command decorator (and a query decorator). A Hub cannot depend on per-web-request instances itself, but must instead depend on another interface whose implementation depends on the per-request instances. The implementation that is injected into the Hub constructor is decorated (via simpleinjector) with a wrapper that begins and disposes of the lifetime scope.

public class CommandLifetimeScopeDecorator<TCommand> : ICommandHandler<TCommand>
{
    private readonly Func<ICommandHandler<TCommand>> _handlerFactory;
    private readonly Container _container;

    public CommandLifetimeScopeDecorator(
        Func<ICommandHandler<TCommand>> handlerFactory, Container container)
    {
        _handlerFactory = handlerFactory;
        _container = container;
    }

    [DebuggerStepThrough]
    public void Handle(TCommand command)
    {
        using (_container.BeginLifetimeScope())
        {
            var handler = _handlerFactory(); // resolve scoped dependencies
            handler.Handle(command);
        }
    }
}

... it is the decorated ICommandHandler<T> instances that depend on per-web-request instances. For more information on the pattern used, read this and this.

Example registration

container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), assemblies);

container.RegisterSingleDecorator(
    typeof(ICommandHandler<>),
    typeof(CommandLifetimeScopeDecorator<>)
);