Showing posts with label SignalR. Show all posts
Showing posts with label SignalR. Show all posts

Saturday, January 11, 2014

Dependency Injection with SignalR and MVC

Thank you to Isaac Abraham for bringing this solution to my attention!

Do not extend DefaultDependencyResolver

How do you practice inversion of control with SignalR? The official SignalR documentation suggests that you extend the DefaultDependencyResolver base class, and then register that as SignalRs dependency resolver.

This however, can have some nasty side effects! In my case, the ConnectionManager.GetHubContext method was not properly resolving my contexts, and thus I was unable to broadcast messages to my hubs clients.

So then, what is a less obtrusive way to inject your dependencies into your hubs?

Instead register an IHubActivator with the DependencyResolver

A simpler solution is just to register a custom HubActivator with the already existing DependencyResolver. This means that instead of completely replacing the SignalR resolver you are instead adding to it.

The HubActivator is only used when trying to resolve a hub; thus the activator can wrap your container of choice and use it to resolve your hub with its dependencies, while leaving the rest of the SignalR pipeline intact.

SignalR Startup with MVC DepenencyResolver

What does this all mean? It means that once you have your dependency injection setup for MVC, you can then create hubs with dependencies using the same container! This MvcHubActivator will use the default System.Web.Mvc.DependencyResolver to resolve its Hubs:

Real Time Web Analytics