Use the default controller container if registered Unity types do not define this current controller

First time with Unity,

I created such a class 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>();
    }
}

The problem is when the AccountController is called (by default the MVC project), it throws an error:

An exception of type "Microsoft.Practices.Unity.ResolutionFailedException" occurred in Microsoft.Practices.Unity.dll, but was not processed in the user code

I see that there is a way to check if the type has been registered, but when I did this check, how do I get the environment to use the default controller?

if (container.IsRegistered(controllerType))

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

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
1

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

, ... .

+1

Source: https://habr.com/ru/post/1527260/


All Articles