Home > C# > A SignalR DepedencyResolver for Microsoft Unity

A SignalR DepedencyResolver for Microsoft Unity

SignalR is a great framework for building real-time web applications. It hooks naturally into ASP.NET MVC and jQuery. Among other extensibility points, it includes support for DI containers. This can be accomplished by overwriting the default Dependency Resolver implementation with one that will rely on your DI container of choice.

Currently, if we look in the official NuGet package repository, we can find implementations for two DI containers (Ninject and StructureMap). But no support for Microsoft Unity. In this short blog post, I want to share my own implementation that relies on Unity:

/// <summary>
/// A SiganlR DependencyResolver that uses Microsoft Unity.
/// </summary>
public class UnityDependencyResolver : DefaultDependencyResolver
{
    private readonly IUnityContainer container;

    public UnityDependencyResolver(IUnityContainer container)
    {
        if(container == null)
            throw new ArgumentNullException("container");

        this.container = container;
    }

    [DebuggerStepThrough] // If Unity cannot resolve a type, it will throw an exception. We don't want this when "Break on exceptions" is activated.
    public override object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (Exception)
        {
            return base.GetService(serviceType);
        }
    }

    [DebuggerStepThrough] // If Unity cannot resolve a type, it will throw an exception. We don't want this when "Break on exceptions" is activated.
    public override IEnumerable GetServices(Type serviceType)
    {
        List result = new List();

        try
        {
            result.AddRange(container.ResolveAll(serviceType));
        }
        finally
        {
            result.AddRange(base.GetServices(serviceType));
        }

        return result;
    }
}
Advertisements
Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: