开发者

MVC - use different controller under specific circumstances

开发者 https://www.devze.com 2023-01-29 09:56 出处:网络
I have a Customer controller that deals with customer products, information and what not.Some products have specialisations that I want handle slightly differently so need a process of doing that.Curr

I have a Customer controller that deals with customer products, information and what not. Some products have specialisations that I want handle slightly differently so need a process of doing that. Currently I have hard coded in if statements to see if a customer has that product or not, and if it has, it'll add the extra navigation elements etc.

What I think might be a better way is to have a Controller that inherits off my customer controller but adds the extra functionality. It'd then be pretty nifty if I could, upon receiving the request, check which Customer derived controller has a function that matches the reques开发者_开发百科t i.e. ViewSpecialProduct and then invokes that as opposed to the vanilla customer controller.

Are there easier ways? If not how do I accomplish the above? I don't know enough about routes and the controller initialisation process yet.

Thanks


You can create a new Controller Factory that derives from DefaultControllerFactory and overrides the GetControllerInstance. I'm not sure how you're performing the customer check but it could look something like this:

public class CustomControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == typeof(DefaultProductController))
        {                
            if(// is special customer)
                return new SpecialProductController();
            else
                return new DefaultProductController();
        }
    }
}

You then set the new ControllerFactory in Global.asax Application_Start via ControllerBuilder.Current:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());

        RegisterRoutes(RouteTable.Routes);
    }


Because of where it occurs in the life cycle, you probably don't want to do this with routing. MvcContrib has code available for a SubController http://jeffreypalermo.com/blog/mvccontrib-latest-release-now-with-subcontroller-support/. Also, you could just create another controller, by either injecting the controller factory reference into the controller, or by creating a controller manually and returning its action, (but if you want this to work, you have to remember to initalize it with the ControllerContext).

0

精彩评论

暂无评论...
验证码 换一张
取 消