我收到以下异常:

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.

当框架尝试构造不是从 ApiController 派生的 Controller 时,例如下面我的简单 HomeController:
 public class HomeController : Controller
        {
            private IUnityContainer _unityContainer;
            public HomeController(IUnityContainer unityContainer)
            {
                _unityContainer = unityContainer;
            }
            public ActionResult Index()
            {
                return View();
            }
        }

我定义了以下 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;
            }
        }

Bootstrapper.Initialize() 是在 Global.asax.cs 的 Application_Start 中执行的最后一行代码?

从 ApiController 派生的 Controller 类不会引发异常。有人可以告诉我我缺少什么吗?

谢谢。

最佳答案

由于我在同一个项目中混合了 Web API 和 MVC4,我还需要确保 Unity.WebApi.UnityDependencyResolver Unity.Mvc4.UnityDependencyResolver 都按照 here 所示进行设置。

我的 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>();
    }

允许 Unity 成功解析 MVC 和 Web API Controller 。为了支持两者,我需要 NuGet 包 Unity.Mvc4 Unity.WebAPI 。希望这不会在路上咬我。

关于c# - 混合 Unity Web API 和 MVC4 UnityDependencyResolvers : No parameterless constructor defined for this object,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20229295/

10-11 01:44