简体   繁体   English

如何使用Unity在Web API 2.0中进行构造函数级DI

[英]How to do constructor level DI in web api 2.0 using Unity

I am using Unity to do dependency injection in ASP.Net MVC by creating a custom controller activator class as, 我正在使用Unity通过在ASP.Net MVC中创建自定义控制器激活器类来进行依赖项注入,

 public class CustomControllerActivator : IControllerActivator
{
    public IController Create(RequestContext requestContext, Type controllerType)
    {
        var controller = default(IController);
        if (controllerType != default(Type))
        {
            controller = ServiceLocator.Current.GetInstance(controllerType) as IController;
        }
        return controller;
    }
}

and then a custom dependency controller resolver class as follows, 然后是一个自定义依赖项控制器解析器类,如下所示:

 public class CustomControllerDependencyResolver : IDependencyResolver
{
    public object GetService(Type serviceType)
    {
        var resolvedObject = default(object);
        if (serviceType == typeof(IControllerActivator))
        {
            resolvedObject = new CustomControllerActivator();
        }

        return resolvedObject;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        var resolvedObjects = default(IEnumerable<Object>);

        resolvedObjects = ServiceLocator.Current.GetInstances(serviceType);
        return resolvedObjects;
    }
}

then I add the following line to global.asax.cs file, 然后将以下行添加到global.asax.cs文件中,

DependencyResolver.SetResolver(new CustomControllerDependencyResolver());

to register my custom dependency resolver. 注册我的自定义依赖项解析器。

The above method holds good for MVC controllers but when I used to do the same for webapi controllers it fails as , An error occurred when trying to create a controller of type 'CustomerController'. 上面的方法对MVC控制器适用,但是当我以前对webapi控制器执行相同操作时,它失败为, 尝试创建类型为'CustomerController'的控制器时发生错误。 Make sure that the controller has a parameterless public constructor. 确保控制器具有无参数的公共构造函数。

The problem is that the MVC and Webapi are working by their own DI so it creates object from the constructor of the controller which must be pram-less, but when you trying to make your own param constructor which will depend on your DI, you will need to install the configs which learn MVC or Webapi to handle your DI in your case you are using Unity so you have to install unity.webapi and this is the code : 问题在于,MVC和Webapi都是通过自己的DI进行工作的,因此它会从控制器的构造函数创建对象,该对象必须是无婴儿车,但是当您尝试创建自己的依赖于DI的参数构造函数时,在使用Unity的情况下,需要安装学习MVC或Webapi的配置来处理DI,因此必须安装unity.webapi,这是代码:

PM> Install-Package Unity.WebAPI -Version 0.10.0 PM>安装软件包Unity.WebAPI-版本0.10.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM