Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc 3- get the current controller instance (not just name)

I know how to get the current controller name

HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

But is there any way to get the current controller instance in some class (not in an action and not in a view)?

like image 672
Alexandre Avatar asked Oct 23 '11 10:10

Alexandre


1 Answers

By default you can only access the current Controller inside a controller with ControllerContext.Controller or inside a view with ViewContext.Context. To access it from some class you need to implement a custom ControllerFactory which stores the controller instance somewhere and retrieve it from there. E.g in the Request.Items:

public class MyControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        var controller = base.CreateController(requestContext, controllerName);
        HttpContext.Current.Items["controllerInstance"] = controller;
        return controller;
    }
}

Then you register it in your Application_Start:

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

And you can get the controller instance later:

public class SomeClass
{
    public SomeClass()
    {
        var controller = (IController)HttpContext.Current.Items["controllerInstance"];
    }
}

But I would find some another way to pass the controller instance to my class instead of this "hacky" workaround.

like image 133
nemesv Avatar answered Nov 03 '22 08:11

nemesv