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.
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
.
This is my favorite. Why?
- Less code than the
SimpleInjectorDependencyResolver
.
- No need to replace the
DefaultDependencyResolver
(a.k.a. GlobalHost.DependencyResolver
), which means even less code.
- 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<>)
);