无法访问Web API 2中的Unity DependencyResolver

时间:2016-10-05 10:53:29

标签: c# asp.net-web-api dependency-injection unity-container unit-of-work

我正在遵循this website中描述的过程,以便为我的一个控制器设置依赖注入的Unity依赖性解析器。这段代码工作正常:

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

上面的代码放在WebApiConfig Register(HttpConfiguration config)方法中。 但是,说明还指定您必须使用此代码:

config.DependencyResolver = new DependencyResolver();

这就是问题所在:DependencyResolver()在当前上下文中不存在。我已经尝试过搜索这个,我也尝试过UnityDependencyResolver(),它也不存在。我正在使用(或尝试使用)名称空间:

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;

DependencyResolver似乎不再存在让我感到困惑。谢谢。

1 个答案:

答案 0 :(得分:2)

instructions指定您应该使用此代码:

config.DependencyResolver = new UnityResolver(container);

UnityResolver类实现IDependencyResolver接口。

添加UnityResolver类

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();
    }
}