Use default controller container if Unity registered types has not got this current controller defined

China☆狼群 提交于 2019-12-11 11:51:33

问题


First time with Unity,

I have set up a class like this and registered in global.asax:

public class UnityControllerFactory : DefaultControllerFactory
{
    private IUnityContainer container;

    public UnityControllerFactory()
    {
        container = new UnityContainer();
        RegisterTypes();
    }

    protected override IController GetControllerInstance(
      System.Web.Routing.RequestContext requestContext, 
      Type controllerType)
    {
        return controllerType == null ?
            null :
            (IController)container.Resolve(controllerType);
    }

    private void RegisterTypes()
    {
        container.RegisterType<IUserRepository, EFUserRepository>();
    }
}

Problem is, when the AccountController (default MVC project comes with) is called, it throws an error:

An exception of type 'Microsoft.Practices.Unity.ResolutionFailedException' occurred in Microsoft.Practices.Unity.dll but was not handled in user code

I can see there is a method to check if a type has been registered, but when I have made that check, how do I force the framework to use the default controller thingy?

if (container.IsRegistered(controllerType))

Here is my routing, as you can see... I want the login page to be the first page people see..

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/",
            defaults: new {
                 controller = "Account",
                 action = "Login",
                 returnUrl = UrlParameter.Optional }
        );
    }
}

回答1:


Implemented a slightly different attempt at the factory:

public class UnityControllerFactory : DefaultControllerFactory
{
    private IUnityContainer container;
    private IControllerFactory defaultControllerFactory;

    public UnityControllerFactory()
    {
        container = new UnityContainer();
        defaultControllerFactory = new DefaultControllerFactory();
        RegisterTypes();
    }

    public override IController CreateController(RequestContext ctx, string controllerName)
    {
        try
        {
            return container.Resolve<IController>(controllerName);
        }
        catch 
        {
            return defaultControllerFactory.CreateController(ctx, controllerName);
        }
    }

    private void RegisterTypes()
    {
        container.RegisterType<IUserRepository, EFUserRepository>();
    }
}

still kicking up errors though... hmm.



来源:https://stackoverflow.com/questions/19897617/use-default-controller-container-if-unity-registered-types-has-not-got-this-curr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!