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.