Microsoft Unity IoC无法运行和ASP.NET mvc4应用程序。为什么?

时间:2013-04-06 11:42:15

标签: asp.net inversion-of-control unity-container ioc-container

我正在尝试将Unity IoC容器设置为ASP.NET mvc4应用程序。 我创建了空项目并使用包管理控制台安装了下一个产品

  • Install-Package Unity
  • 安装包Unity.Mvc4

一切顺利完成。但在我运行我的应用程序后,我有异常

  

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。   异常详细信息:System.MissingMethodException:无法创建接口的实例。

这是简单的代码。 的global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        Bootstrapper.Initialise();
    }
}

public interface IA
{
    void test();
}
public class A : IA
{
    public A() { }
    public void test()
    {
        throw new NotImplementedException();
    }
}

HomeController.cs

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index(IA a)
    {
        return View();
    }

}

Bootstrapper.cs:

public static class Bootstrapper
{
    public static void Initialise()
    {
        var container = BuildUnityContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

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

        container.RegisterType<IA, A>();          

        return container;
    }
}

我做错了什么以及为什么代码不起作用?

堆栈追踪:

  

堆栈跟踪:[MissingMethodException:无法创建接口的实例。]      System.RuntimeTypeHandle.CreateInstance(RuntimeType类型,Boolean publicOnly,Boolean noCheck,Boolean&amp; canBeCached,RuntimeMethodHandleInternal&amp; ctor,Boolean&amp; bNeedSecurityCheck)+0      System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,Boolean skipCheckThis,Boolean fillCache)+98      System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,Boolean skipVisibilityChecks,Boolean skipCheckThis,Boolean fillCache)+241      System.Activator.CreateInstance(Type type,Boolean nonPublic)+69      System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext,Type modelType)+199      System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext,ModelBindingContext bindingContext)+572      System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)+454      System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext,ParameterDescriptor parameterDescriptor)+317      System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext,ActionDescriptor actionDescriptor)+117      System.Web.Mvc.Async。&lt;&gt; c_ DisplayClass25.b _1e(AsyncCallback asyncCallback,Object asyncState)+476      System.Web.Mvc.Async.WrappedAsyncResult 1.Begin(AsyncCallback callback, Object state, Int32 timeout) +124 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +304 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30 System.Web.Mvc.Async.WrappedAsyncResult 1.Begin(AsyncCallback回调,对象状态,Int32超时)+124      System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback,Object state)+389      System.Web.Mvc.Async.WrappedAsyncResult 1.Begin(AsyncCallback callback, Object state, Int32 timeout) +124 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +319 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +76 System.Web.Mvc.Async.WrappedAsyncResult 1.Begin(AsyncCallback回调,对象状态,Int32超时)+124      System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext,AsyncCallback回调,对象状态)+251      System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,AsyncCallback回调,对象状态)+50      System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context,AsyncCallback cb,Object extraData)+16      System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+8837208      System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+184

1 个答案:

答案 0 :(得分:4)

我完全不知道你的错是什么,但这里的设置对我有用;

public static class Bootstrapper
{
    public static void Initialise()
    {
        var container = BuildUnityContainer();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();
        container.RegisterType<ICategoryRepository, CategoryRepository>(new HierarchicalLifetimeManager());
        return container;
    }
}

Global.asax中

 Bootstrapper.Initialise();

现在,在我的控制器构造函数中;

ICategoryRepository _catRepo;

public CategoryController(ICategoryRepository catRepo)
{
    _catRepo = catRepo;
}
public ActionResult Index()
{
    ViewBag.CategoriesList = _catRepo.GetAllCategories();
    return View();
}