In my last post SignalR 2.0 Dependency Injection With StructureMap I added a IoC container to SignalR using StructureMap, since then I've learned a little more about this method of configuring DI in SignalR which I would like to share. You can find the code for this post here.

By default when you update the dependency resolver used in the HubConfiguration it will prevent those hubs from accessing any configuration settings you set in GlobalHost. For example if you attempt this:

    GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(5);

Your configuration will not get set as you would expect. (If you're wondering why you'd edit this value, I'll get to that in the next post, hint: iPad).

What is going on?

Take a look at the SignalR code on GitHub, I'll use the example of LongPollingTransport:

public LongPollingTransport(HostContext context, IDependencyResolver resolver)  
            : this(context,
                   resolver.Resolve<JsonSerializer>(),
                   resolver.Resolve<ITransportHeartbeat>(),
                   resolver.Resolve<IPerformanceCounterManager>(),
                   resolver.Resolve<ITraceManager>(),
                   resolver.Resolve<IConfigurationManager>())

As you can see from above, when SignalR spins up a new a instance of a transport it is using our custom resolver. As opposed to the GlobalHost constructor which is doing this:

private static readonly Lazy<IDependencyResolver> _defaultResolver = new Lazy<IDependencyResolver>(() => new DefaultDependencyResolver());

//(Code Omitted For Brevity)

public static IConfigurationManager Configuration  
{
    get
    {
        return DependencyResolver.Resolve<IConfigurationManager>();
    }
}

What this means is that by default SignalR is going to use different resolver instances for GlobalHost (DefaultDependencyResolver) and our hubs (our custom resolver).

Luckily we can work around this by setting the dependency resolver on GlobalHost instance.

//Set GlobalHost dependency resolver to ensure hubs utilize the same configuration.
GlobalHost.DependencyResolver = resolver;  

After setting this you GlobalHost configuration settings will be propagated to your hubs and you're good to go!

comments powered by Disqus

About Author

Jerod Krone

Jerod Krone