3

I have this MVC4 controller (ControllerB):

public class MyControllerB : Controller
{
    public bool Check(string actionName, ControllerBase controllerBase)
    {
        ControllerContext controllerContext = new ControllerContext(this.ControllerContext.RequestContext, controllerBase);

        ...
    }
}

I'm calling ControllerB's Check method from "ControllerA", like so:

bool b = new MyControllerB().Check("Index", this);

I get Object reference not set to an instance of an object because this.ControllerContext is null.

If I move the Check method to ControllerA, it works just fine. But I need this method to be in a different controller. How can I fix my code so that ``this.ControllerContext` will not be null?

Jon Adams
  • 24,464
  • 18
  • 82
  • 120
Administrateur
  • 891
  • 4
  • 13
  • 29

1 Answers1

5

The ControllerContext is null because you are manually creating the ControllerB instance from ControllerA.

Normally, IController instances are created by the registered IControllerFactory, typically System.Web.Mvc.DefaultControllerFactory. The controller factory will new() the instance and initialize settings properly.

As @DZL says, it is normally much better to have both controllers subclass a BaseController class, which can have shared initialization and shared properties and methods.

I don't understand the business logic of what you are trying to do, but here's a code example of using the base class from the 2 controllers:

namespace MyNamespace.Controllers
{
    public class MyControllerBase : Controller
    {
        public bool Check(string actionName, ControllerBase controllerBase)
        {
            ControllerContext controllerContext = new ControllerContext(this.ControllerContext.RequestContext, controllerBase);
            return false;
        }
    }
    public class MyControllerA : MyControllerBase
    {
        ActionResult Index()
        {
            bool b = base.Check("Index", this);
            return View();
        }
    }
    public class MyControllerB : MyControllerBase
    {
        ActionResult Index()
        {
            bool b = base.Check("Index", this);
            return View();
        }
    }
}

If you really want to do exactly what you are asking, you'll have to call IControllerFactory.CreateController(requestContext, controllerName) instead of new ControllerB(), but that is a really convoluted way of doing things - I wouldn't recommend it.

AlexB
  • 7,302
  • 12
  • 56
  • 74
Raul Nohea Goodness
  • 2,549
  • 23
  • 24
  • Found the answer here: [http://forums.asp.net/t/1409129.aspx](http://forums.asp.net/t/1409129.aspx) Don't know if this is the most efficient way... and I don't know of another way at this point. Any ideas? – Administrateur Sep 27 '13 at 19:15