将依赖注入Web API控制器

时间:2016-01-21 17:41:58

标签: asp.net-mvc-4 asp.net-web-api dependency-injection unity-container

我想将Unity容器注入WebController。

我有UnityDependencyResolver:

public class UnityDependencyResolver : IDependencyResolver
{
    readonly IUnityContainer _container;

    public UnityDependencyResolver(IUnityContainer container)
    {
    this._container = container;
    }

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

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

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

然后,在我的Global.asax中添加以下行:

var container = new UnityContainer();
container.RegisterType<IService, Service>
(new PerThreadLifetimeManager()).RegisterType<IDALContext, DALContext>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

然后,如果我在Web控制器中使用以下内容:

private IService _service;

public HomeController(IService srv)
{
    _service = srv;
}

工作正常。

但是我想把它注入到WebAPI Controller中,所以如果我这样做的话:

private IService _service;

public ValuesController(IService srv)
{
    _service = srv;
}

它不起作用,它说构造函数没有定义。 好的,我再创建一个构造函数:

public ValuesController(){}

在这种情况下,它只使用这个构造函数,而不是我应该注入统一容器的那个。

请告知。

1 个答案:

答案 0 :(得分:0)

在WebApiConfig中添加:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Routes and other stuff here...

        var container = IocContainer.Instance; // Or any other way to fetch your container.
        config.DependencyResolver = new UnityDependencyResolver(container);
    }
}

如果你想要相同的容器,可以将它保存在一个静态变量中,如下所示:

public static class IocContainer
{
    private static readonly Lazy<IUnityContainer> Container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        return container;
    });

    public static IUnityContainer Instance
    {
        get { return Container.Value; }
    }
}

可在此处找到更多信息:

http://www.asp.net/web-api/overview/advanced/dependency-injection

在旁注中,我还可以推荐nuget-package Unity.Mvc。它会为UnityWebActivator添加PerRequestLifetimeManager和支持。

https://www.nuget.org/packages/Unity.Mvc/