0

Well I am trying to create a constructor for my ASP.NET MVC 5 Controller, which is used to initialize properties such as Repository, Mapper and Services. This is the code I write as below, for a group page:

    public ApplicationDbContext Db { get; private set; }
    public GroupMapper Mapper { get; private set; }
    public ImageUploadService ImageUploader { get; private set; }

    public GroupsController()
    {
        this.Db = new ApplicationDbContext();
        this.Mapper = new GroupMapper(Db);
        this.ImageUploader = new ImageUploadService(this.Server);
    }

The issue here is, the properties for parent controller aint initialized and therefore cannot be used in child constructor. In this case, the property is 'this.Server', but this value does not exist until the object is completed. If I use 'this.Server' in a controller action, it is available. But if I use it in the constructor, it is not, and instead returns a null reference.

I have no idea why ASP.NET MVC behaves this way, I thought when I create a child controller all parent properties are already there, but I was wrong. This leads to an issue when I use the ImageUploader service, as the dependency 'this.Server' is null and I get tons of errors.

So does anyone know how to fix or get by this issue? It really surprises me and I have no idea what I can do.

4
  • Can you please show small piece of class where "Server" defined/initialized? Commented May 4, 2015 at 4:06
  • 3
    Side note: consider using DI framework instead - like. Unity or Ninject to configure dependencies between objects. Commented May 4, 2015 at 4:07
  • It is in the MVC's parent constructor class in the .NET framework, I cannot show the code since I cannot view the implementation. The interface is available though, just a property with getter and no setter. Commented May 4, 2015 at 4:11
  • 1
    I think the accepted answer to stackoverflow.com/questions/633059/… will get you where you want to go. Commented May 4, 2015 at 4:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.