2
votes

I have a MVC 4 web application using .net 4.5.1 ,which is working good in local but when I deploy the site to the live server it will throw an exception when I invoke the controller .The exception is only thrown when I put a constructor on the controller.I tested the application by removing the constructor from the controller it will working fine .I cant figure out why this happen .

Here is my controller :

namespace Test.Controllers
{
  public class TestController : Controller
  {
     private readonly ICountryService _countryService;

     public TestController()
     {
         _countryService=new CountryService();
     }

     // GET: /Test/
     public ActionResult Index()
     {

          var items = _countryService.GetAllCountries();
        return View(items.ToList());
     }
  }
}

Here is the exception :

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] Test.Controllers.TestController..ctor() +74

[TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232 System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +6 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55

[InvalidOperationException: An error occurred when trying to create a controller of type 'Test.Controllers.TestController'. Make sure that the controller has a parameterless public constructor.] System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +77 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +191 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Why this happen when I deploy the website into live server.

Would appreciate any help offered. Let me know if you need any other information to help answer this question

2
Perhaps Response is null a that point? - Johan

2 Answers

1
votes

This is because your Response object is null. You can also notice that in the browser, (where the exception occurs) just above the stack trace.

Edit: & btw, if you notice, your HttpContext object would also be null

instead you can try:

 var res = System.Web.HttpContext.Current.Response;
 res.Write("hi");

This works ;)

1
votes

It's a NullReferenceException in your constructor. That means you're trying to access an object that's not yet been instantiated. The only object you're accessing is the Response object, so the logical conclusion here is that the Response member in your controller is null when your controller is instantiated. This is because the context-related data (Controller.Request, Controller.Response, etc.) does not get populated until the Initialize method gets called.

My question is, why would you want to write directly to the Response in ASP.NET MVC? It sounds like a bad habit picked up from ASP.NET WebForms.

Here's how to do dependency injection using Ninject:

NinjectWebCommon.cs:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ICountryService>().To<CountryService>();
    // other bindings....
    //...
}

TestController.cs

public class TestController : Controller
{
    private readonly ICountryService _countryService;

    public TestController(ICountryService countryService)
    {
        _countryService = countryService;
    }

    // GET: /Test/
    public ActionResult Index()
    {
        var items = _countryService.GetAllCountries();
        return View(items.ToList());
    }

}