统一的IoC不依赖注入到网页API控制器 [英] Unity IoC does not inject dependency into Web API Controller

查看:591
本文介绍了统一的IoC不依赖注入到网页API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的使用Unity,但我的问题是,每当我打电话给我的web服务,我得到一个异常说明

确保控制器具有一个无参数的公共构造

我已经按照多个教程和我仍然得到同样的问题。

在我WebApiConfig类的注册功能,我有

  VAR集装箱=​​新UnityContainer();
container.RegisterType&所述; IValidator,验证>(新HierarchicalLifetimeManager());
config.DependencyResolver =新UnityResolver(容器);

下面是我UnityResolver类

 使用Microsoft.P​​ractices.Unity;
使用系统;
使用System.Collections.Generic;
使用System.Web.Http.Dependencies;公共类UnityResolver:的IDependencyResolver
{
    保护IUnityContainer容器;    公共UnityResolver(IUnityContainer容器)
    {
        如果(集装箱== NULL)
        {
            抛出新的ArgumentNullException(容器);
        }
        this.container =容器;
    }    公共对象GetService的(类型的serviceType)
    {
        尝试
        {
            返回container.Resolve(的serviceType);
        }
        赶上(ResolutionFailedException)
        {
            返回null;
        }
    }    公共IEnumerable的<对象> GetServices(类型的serviceType)
    {
        尝试
        {
            返回container.ResolveAll(的serviceType);
        }
        赶上(ResolutionFailedException)
        {
            返回新的List<对象>();
        }
    }    公共IDependencyScope BeginScope()
    {
        VAR孩子= container.CreateChildContainer();
        返回新UnityResolver(小孩);
    }    公共无效的Dispose()
    {
        container.Dispose();
    }
}

我尚未注册任何控制器,因为我并不需要每天都这样教程索赔。这是我的实际控制人。

 公共类控制器:ApiController
{
    私人IValidator _validator;    公共控制器(IValidator验证)
    {
        this._validator =验证;
    }    [HttpPost]
    公共无效ReceiveIPN()
    {    }
}

有没有人有任何想法,我可以做错了什么?谢谢!

编辑1:这里是Validator类的执行。这是pretty空的,因为我不想在这里介绍一个bug,直到我解决了统一的问题。

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
公共类验证:IValidator
{
    公共BOOL ValidateIPN(字符串体)
    {
        抛出新NotImplementedException();
    }
}

编辑2:这里是整个错误响应,我得到当我尝试调用使用招网络API路线


  

{消息:发生错误,exceptionMessage:错误
  试图创建类型的控制器控制器时发生。使
  确保该控制器具有一个无参数的公共
  构造,exceptionType。:System.InvalidOperationException,堆栈跟踪:
  在
  System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HTT prequestMessage
  要求,HttpControllerDescriptor controllerDescriptor,类型
  controllerType)在
  System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HTT prequestMessage
  请求)的
  System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext(),的InnerException:{消息:一个
  发生错误,exceptionMessage:类型Project.Controller
  不具有默认
  构造函数,exceptionType:System.ArgumentException,堆栈跟踪:
  在System.Linq.Ex pressions.Ex pression.New(类型类型)在
  System.Web.Http.Internal.TypeActivator.Create [TBASE](类型
  instanceType)在
  System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HTT prequestMessage
  要求,类型controllerType,Func`1&安培;激活剂)在
  System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HTT prequestMessage
  要求,HttpControllerDescriptor controllerDescriptor,类型
  controllerType)}}



解决方案

所以,敲我的头撞墙了几个小时之后,我发现这是不工作,因为我有一个OWIN /武士刀Startup.cs类在我的项目。现在,我不知道到底发生了什么在这里,所以任何更多的信息将是巨大的。

基本上,因为我是用OWIN /武士刀,我有创建了一个新HttpConfiguration对象,并配置它Startup.cs文件,类似于它是如何在WebApiConfig.cs类完成。

 私人无效ConfigureWebApi(HttpConfiguration配置)
{
    config.MapHttpAttributeRoutes();
    VAR集装箱=​​新UnityContainer();
    container.RegisterType< IValidator,验证>();
    config.DependencyResolver =新UnityDependencyResolver(容器);    VAR jsonFormatter = config.Formatters.OfType< JsonMediaTypeFormatter()第一();
    jsonFormatter.SerializerSettings.ContractResolver =新CamelCasePropertyNamesContractResolver();
}

它看起来像code首先通过WebApiConfig的注册函数运行,然后将覆盖HttpConfiguration对象,在Startup.cs文件生成的之一。我在这里将我的容器设置的东西,以便为它工作。

对不起,我没有之前弹出OWIN东西。这是相当新的给我,我不知道这是相关的。希望这样可以节省别人说我刚刚经历过的痛苦。

I'm very new to using Unity, but my problem is that whenever I call my web service, I get an exception stating that

"Make sure that the controller has a parameterless public constructor"

I've followed multiple tutorials and I still get the same issue.

In the Register function of my WebApiConfig class, I have

var container = new UnityContainer();
container.RegisterType<IValidator, Validator>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);

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

I have not registered any controllers, as every tutorial claims that I don't need to do this. Here is my actual controller

public class Controller: ApiController
{
    private IValidator _validator;

    public Controller(IValidator validator)
    {
        this._validator = validator;
    }

    [HttpPost]
    public void ReceiveIPN()
    {

    }
}

Does anyone have any ideas as to what I can be doing wrong? Thanks!

EDIT 1: Here is the "implementation" of the Validator class. It's pretty empty, because I didn't want to introduce a bug here until I resolved the Unity issue.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public class Validator: IValidator
{
    public bool ValidateIPN(string body)
    {
        throw new NotImplementedException();
    }
}

EDIT 2: Here is the entire error response I get when I attempt to call the web api route using Fiddler

{"message":"An error has occurred.","exceptionMessage":"An error occurred when trying to create a controller of type 'Controller'. Make sure that the controller has a parameterless public constructor.","exceptionType":"System.InvalidOperationException","stackTrace":" at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()","innerException":{"message":"An error has occurred.","exceptionMessage":"Type 'Project.Controller' does not have a default constructor","exceptionType":"System.ArgumentException","stackTrace":" at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}}

解决方案

So, after hours of banging my head against a wall, I've found that this wasn't working because I had an OWIN/Katana Startup.cs class in my project. Now I don't know exactly what's going on here, so any more information would be great.

Basically, since I was using OWIN/Katana, I had a Startup.cs file that created a new HttpConfiguration object and configured it, similar to how it's done in the WebApiConfig.cs class.

private void ConfigureWebApi(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
    var container = new UnityContainer();
    container.RegisterType<IValidator, Validator>();
    config.DependencyResolver = new UnityDependencyResolver(container);

    var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter().First();
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}

It looks like the code first runs through the WebApiConfig's Register function, and THEN overrides that HttpConfiguration object with the one generated in the Startup.cs file. I had to move my container setup stuff here in order for it to work.

Sorry that I didn't bring up the OWIN stuff before. This is fairly new to me and I didn't realize it was relevant. Hopefully this saves someone else the pain that I've just been through.

这篇关于统一的IoC不依赖注入到网页API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆