2

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

Mussammil
  • 864
  • 4
  • 16
  • 38
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ben Robinson Oct 29 '14 at 09:56
  • 1
    Perhaps `Response` is null a that point? – Johan Oct 29 '14 at 09:56

2 Answers2

1

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

Zeeshan
  • 2,884
  • 3
  • 28
  • 47
1

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

}

Radu Porumb
  • 785
  • 5
  • 7
  • actually I dont want to use the Response I just want to instantiate my service inside the constructor you can see that on the commented code when uncomment that this exception is thrown – Mussammil Oct 29 '14 at 10:13
  • 1
    @Mussammil Why don't you just inject it into the controller using Dependency Injection? – Radu Porumb Oct 29 '14 at 10:16
  • Porumbo , I am new to asp.net mvc I dont know much about Dependency injection ,If I use dependency injection is this will degrade my application performance ? – Mussammil Oct 29 '14 at 10:25
  • 1
    Not at all. And it's dead simple to enable. Just get the Ninject.MVC5 package off NuGet, add your bindings in App_Start/NinjectWebCommon.cs and change your controller to take an ICountryService as the parameter for its constructor. The pattern you've already set up (with a Service layer and using interfaces) is perfectly suited to DI. – Radu Porumb Oct 29 '14 at 11:03
  • actually my application is a simple application with a few controllers and few views so using Ninject in my app wont cause any performance lag ? u said add binding in NinjectWebCommon.cs ,Is I need to reference all my service classes here and at runtime the ninject will automatically resolve right ? – Mussammil Oct 29 '14 at 11:12
  • ,what are the other typical objects which register on the NinjectWebCommon.cs other than service – Mussammil Oct 29 '14 at 17:16
  • 1
    @Mussammil Anything you want to inject into a Controller via the constructor, as per my example. You can also chain-inject objects, like if your `CountriesService` takes a `CountriesRepository` argument in the constructor, you can have it take an `ICountriesRepository` which you bind to `CountriesRepository` in NinjectWebCommon.cs. – Radu Porumb Oct 29 '14 at 21:51