简体   繁体   English

混合Unity Web API和MVC4 UnityDependencyResolvers:没有为此对象定义无参数构造函数

[英]Mixing Unity Web API and MVC4 UnityDependencyResolvers: No parameterless constructor defined for this object

I am getting the following exception: 我收到以下异常:

No parameterless constructor defined for this object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

when the framework attempts to construct controllers that do not derive from ApiController, such as my simple HomeController below: 当框架尝试构造不是从ApiController派生的控制器时,例如下面的简单HomeController:

 public class HomeController : Controller
        {
            private IUnityContainer _unityContainer;
            public HomeController(IUnityContainer unityContainer)
            {
                _unityContainer = unityContainer;
            }
            public ActionResult Index()
            {
                return View();
            }
        }

I have the following Boostrapper.cs class defined: 我定义了以下Boostrapper.cs类:

     public static class Boostrapper
        {
            public static void Initialize()
            {
                var container = BuildUnityContainer();
                GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);                          
            }

            private static IUnityContainer BuildUnityContainer()
            {
                var container = new UnityContainer();
                RegisterTypes(container);
                return container;
            }
        }

and Bootstrapper.Initialize() is the last line of code executed within Application_Start of Global.asax.cs? 和Bootstrapper.Initialize()是Global.asax.cs的Application_Start中执行的最后一行代码?

Exception is not thrown on controller classes that derive from ApiController. 从ApiController派生的控制器类不会抛出异常。 Could someone please advise on what I am missing? 有人可以告诉我我错过了什么吗?

Thanks. 谢谢。

Since I am mixing Web API and MVC4 within the same project, I need to also ensure that Unity.WebApi.UnityDependencyResolver and Unity.Mvc4.UnityDependencyResolver are both setup as indicated here . 由于我在同一个项目中混合Web API和MVC4,我还需要确保Unity.WebApi.UnityDependencyResolverUnity.Mvc4.UnityDependencyResolver都按照此处的说明进行设置。

My Boostrapper.cs which now looks like this: 我的Boostrapper.cs现在看起来像这样:

    public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();
      GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      return container;
    }

 private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();
      RegisterTypes(container);
      return container;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IAgencyResolver, AgencyByNameResolver>("ByName");
        container.RegisterType<IAgencyResolver, AgencyByCdeCodeResolver>("ByCode");
        container.RegisterType<IAgencyRepository, AgenciesRepository>();            
    }

allows both MVC and Web API controllers to be resolved successfully by Unity. 允许Unity成功解析MVC和Web API控制器。 To support both, I need NuGet packages Unity.Mvc4 and Unity.WebAPI . 为了支持这两者,我需要NuGet包Unity.Mvc4Unity.WebAPI Hoping this does not bite me down the road. 希望这不会让我受伤。

I think you need something like this... 我觉得你需要这样的东西......

private static IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();

    // register all your components with the container here
    container.RegisterType<Interface, ClassThatImplementsInterface>();

    return container;
}

This tells your runtime which Concrete class to use when the Interface is present. 这告诉runtimeInterface存在时要使用哪个Concrete class

EDIT : Based on comments 编辑 :基于评论

Basically, you are telling the runtime which concrete type implements your interface(s) . 基本上,您告诉运行时哪个concrete类型实现了您的interface(s) So, if you had an interface IRepository and you had two implementations, MockRepo & EFRepo . 所以,如果你有一个接口IRepository ,你有两个实现, MockRepoEFRepo Your tests would likely pass MockRepo to any constructors that require it, but your DI would be responsible for registering the Interface against a runtime repository, in this case, EFRepo . 您的测试可能会将MockRepo传递给任何需要它的构造函数,但您的DI将负责针对运行时存储库(在本例中为EFRepo注册接口。

Obviously, during some testing of the application (ie you browsing the site), you might have the registration of the interface set up to use MockRepo , and then once you're ready to deploy, you can switch back to EFRepo in one location. 显然,在对应用程序进行一些测试(即浏览站点)时,您可能已将接口注册设置为使用MockRepo ,然后在准备好部署后,您可以在一个位置切换回EFRepo

For me I had 对我来说,我有

Unity.WebAPI Unity.WebAPI

Already installed and I was using API controllers and decided to create some views for the API, all I needed to do is 已安装,我正在使用API​​控制器,并决定为API创建一些视图,我需要做的就是

install-package Unity.Mvc 安装包Unity.Mvc

and when promoted for the UnityConfig over write I said no as my Interface to Concrete classes where already functioning as required. 当我为UnityConfig提升而不是写作时,我说不是我的接口到Concrete类已经按要求运行了。 This worked without any other work or setup. 这没有任何其他工作或设置。

My Project is running .NET 4.5.1 MVC 5.1.2 . 我的项目正在运行.NET 4.5.1 MVC 5.1.2 Was very simple and did not effect the API functionality in any way. 非常简单,并没有以任何方式影响API功能。

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

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