Tee See Tee See - 2 months ago 15
C# Question

Not Able to Access Unity DependencyResolver in Web API 2

I am following the procedures described on this website in order to set up a Unity Dependency Resolver for Dependency Injection into one of my controllers. This code works fine:

var container = new UnityContainer();
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());


The above code is placed in the WebApiConfig
Register(HttpConfiguration config)
method.
However, the instructions also specify that you must use this code:

config.DependencyResolver = new DependencyResolver();


This is where the problem is: DependencyResolver() does not exist in the current context. I've tried searching for this and I also tried UnityDependencyResolver() which also does not exist. I am using (or have tried using) namespaces:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Microsoft.Practices.Unity;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using URLShortener.Models;
using Microsoft.Practices.Unity;
using System.Web.Http.Dependencies;


The DependencyResolver does not seem to exist anymore which has me baffled. Thank you.

Answer

The instructions specify that you should use this code:

config.DependencyResolver = new UnityResolver(container);

The UnityResolver class implements the IDependencyResolver interface.

And add the UnityResolver class

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }
}