当前类型是一个接口,无法构造

时间:2015-12-09 12:26:24

标签: c# asp.net-mvc unity-container

我刚刚开始使用Unity作为DependencyInjector。 我一直使用温莎城堡。

我试图做以下事情。 在我的global.asax中,我有以下代码:

DIContainerConfig.RegisterDependencies();

在我的DIContainerConfig中,我有以下代码:

 internal static void RegisterDependencies()
{
    //Initialize IoC container/Unity
    ManagerInstaller.Initialise();
    RepositoryInstaller.Initialise();

    //Register our custom controller factory
    ControllerBuilder.Current.SetControllerFactory(typeof(ControllerInstaller));

}

My RepositoryInstaller如下所示:

public static IUnityContainer Initialise()
{
    var container = BuildUnityContainer();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    return container;
}
private static IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();
    container.RegisterType<IStudentsRepository, StudentsRepository>();
    MvcUnityContainer.Container = container;
    return container;
}

我的ControllerInstaller:

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
    try
    {
        if (controllerType == null)
            throw new ArgumentNullException("controllerType");

        if (!typeof(IController).IsAssignableFrom(controllerType))
            throw new ArgumentException(string.Format(
                "Type requested is not a controller: {0}",
                controllerType.Name),
                "controllerType");

        return MvcUnityContainer.Container.Resolve(controllerType) as IController;
    }
    catch
    {
        return null;
    }

}

现在,当我调试应用程序时,我已进入控制器安装程序,但我收到了错误:

  

当前类型,是一个接口,无法构造。你错过了类型映射吗?

我做错了什么?

我在这一行得到错误: 将MvcUnityContainer.Container.Resolve(controllerType)作为IController返回;

这是堆栈跟踪:

[InvalidOperationException:IControllerFactory&#39; Latin.Configuration.Installers.ControllerInstaller&#39;没有为名称&#39;学生&#39;返回控制器。    System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext,IController&amp; controller,IControllerFactory&amp; factory)+331    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext,AsyncCallback回调,对象状态)+72    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,AsyncCallback回调,对象状态)+67    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context,AsyncCallback cb,Object extraData)+30    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+103    System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+155

0 个答案:

没有答案