Sorry for the vague title. I’ll explain what I’m trying to get working.
My Admin View uses an Admin ViewModel which in turn calls an Admin Service which is a collection of Admin Repositories. For the sake of simplicity lets say that there is only one repository referenced by the Admin Service.
When constructing my Admin View Model the top of my class looks like this
public class adminMenuVM
{
private readonly IAdminMenuService menuService;
public adminMenuVM(IAdminMenuService adminMenuService)
{
this.menuService = adminMenuService;
}
public adminMenuVM()
{
menuItems = getMenuItems();
menuCats = getMenuCats();
}
}
Where getMenuItems and getMenuCats are two methods that use the service to retrieve data which is then set for the view model.
My problem is that when I run the app I get the error “Object Reference not set to instance of an object”. Now I know that this is because the adminMenuVM() is called by the viwModel and not the constructor initializing the service.
My question is how can I ensure that the service constructor is called and does its thing when my view model is called?
I’ve tried using :this on the parameterless constructor but it wont allow me to assign an interface since you can’t create a new instance of an interface.
Edit @ 18:49
I’ve had a thought but don’t know how to implement it. Can anyone advise on how I could “Constructor Chain” or if it is possible? My thought is to chain the parameterless constructor to service constructor this ensuring it gets called. I may be way off but would be grateful for yer help.
Managed to figure this one out. Its not the cleanest solution but I can’t see any other way to do it. I’ll stick this in to help anyone else who comes across this issue.
The issue boiled down to passing the current instance of the service interface to the ViewModel. The only place I could find that the instance was being set was the constructor of my controller. So very simply I declared a public global variable of the interface service type and saved the instance to that. The current instance persits and can be passed to the constructor of my viewmodel and satisfy the viewmodel constructors requirement. To clarify I’ve included an example of the controller and a viewmodel.
Controller:
ViewModel: