Unity.WebApi |确保控制器具有无参数的公共构造函数 [英] Unity.WebApi | Make sure that the controller has a parameterless public constructor

查看:4157
本文介绍了Unity.WebApi |确保控制器具有无参数的公共构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET WebApi解决方案中使用Unity.WebApi NuGet软件包(Unity 4.0.1和Unity.WebApi 5.2.3)。我遇到的问题是,当尝试运行代码时,我会收到错误:确保控制器具有无参数的公共构造函数。我在这里搜索过类似的线程,但是我找不到符合我的问题的任何线程。

I am using the Unity.WebApi NuGet package (Unity 4.0.1 and Unity.WebApi 5.2.3) in an ASP.NET WebApi solution. The issue I am facing is that when attempting to run the code, I get the error: Make sure that the controller has a parameterless public constructor. I've searched similar threads here, but I couldn't find any thread that matched my issue.

请不要只说添加无参数的构造函数,因为它显示你显然不知道IoC是什么,为什么这个声明绝对没有意义,并且击败了IoC的目的。我说这个,因为我看到了很多其他线程,我看过迄今为止。

Please don't just say "Add a parameterless constructor" because it shows you obviously have no clue what IoC is and why that statement makes absolutely no sense and defeats the purpose of IoC. I say this because I saw this on a lot of the other threads I've looked at thus far.

这是我的Startup.cs(我正在使用Owin,所以我没有一个Global.asax):

This is my Startup.cs (I'm using Owin, so I do not have a Global.asax):

public void Configuration(IAppBuilder app) {
    var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();

        // Registering unity stuff
        UnityConfig.RegisterComponents();

        app.UseWebApi(config);
}

这是我的UnityConfig.cs:

This is my UnityConfig.cs:

public static class UnityConfig {
    public static void RegisterComponents() {
        var container = new UnityContainer();
            // Register controller
            container.RegisterType<MyController>();

            // Register interface
            container.RegisterType<IService, Service>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

这是我的API控制器:

This is my API Controller:

public class MyController : ApiController {
    private IService service

    public MyController(IService service) {
        this.service = service;
    }

    public IHttpActionResult Get() {
        return Ok("All systems go!");
    }
}

编辑

我使用了语句,因为人们很难理解,无论使用语句是否存在,都会出现问题。

I took the using statements out because people are having a hard time understanding that the issue occurs whether or not the using statements are there.

推荐答案

根据我的经验,发生这种情况时有两种不同的情况。

In my experience there's 2 different scenarios when this occur.

1。
确保服务构造函数中的所有参数都可以解决。是否有任何您尚未注册的依赖项?

1. Make sure that all parameters in the Service constructor can be resolved. Does it have any dependencies that you haven't registered?

确保控制器在Unity中有一个无参数的公共构造函数

2。
确保使用Web API注册Unity。像这样:

2. Make sure to register Unity with Web API. Like so:

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

这里的示例:

将依赖关系插入Web API控制器

http://codeclimber.net.nz/archive/2015/02/20/Using-Entity-Framework-within-an-Owin-hosted-Web -API-with.aspx

编辑1:

作为@ NightOwl888在评论中提到,你不应该处置容器。注册在容器上注册,当容器被处理时,它将不知道如何解决依赖关系。可能会导致您看到的错误。

As @NightOwl888 mentioned in the comments, you should not dispose the container. The registrations are registered on the container, and when the container is disposed it will not know how to resolve the dependencies. It may result in the error you are seeing.

编辑2:

因为你使用Owin,你应该可以这样做:

Since you're using Owin you should be able to do something like this:

    public void Configuration(IAppBuilder appBuilder) 
    { 
      // Configure Web API for self-host. 
      HttpConfiguration config = new HttpConfiguration();
      config.DependencyResolver = new UnityDependencyResolver(
          UnityConfig.GetConfiguredContainer());

      config.Routes.MapHttpRoute( 
                    name: "DefaultApi", 
                    routeTemplate: "api/{controller}/{id}", 
                    defaults: new { id = RouteParameter.Optional } 
                ); 

      appBuilder.UseWebApi(config); 
    }

并将您的UnityConfig更新为:

And update your UnityConfig to this:

    public static class UnityConfig {
       public static IUnityContainer GetConfiguredContainer() {
            var container = new UnityContainer();
            // Register controller
            container.RegisterType<MyController>();

            // Register interface
            container.RegisterType<IService, Service>();

            //This is done in Startup instead.
            //GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
            return container;
    }
}

从这个来源:
如何在OwinStartup中使用DI容器

http:// damienbod .com / 2013/10/01 / self-host-webapi-with-owin-and-unity /


这个方法,HttpConfiguration.DependencyResolver设置为
UnityDependencyResolver实例。这是必需的,以便在webApi控制器中可以使用引用
注入。
UnityDependencyResolver类与
Unity.WebApi.UnityDependencyResolver类完全相同。 Unity.WebApi不使用
,因为这是一个自我托管的OWIN应用程序。

In this method, the HttpConfiguration.DependencyResolver is set to a UnityDependencyResolver instance. This is required so that contructor injection can be used in the webApi controllers. The UnityDependencyResolver class is exactly the same as the Unity.WebApi.UnityDependencyResolver class. Unity.WebApi is not used because this is a self hosted OWIN application.

这篇关于Unity.WebApi |确保控制器具有无参数的公共构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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