my problem is this:
I have a base class
public abstract class ViewModelBase
which contains an abstract method "RegisterCommands"
protected abstract void RegisterCommands();
All my Derived classes must, obviously, implements this method, for example my LoginViewModel has
protected override void RegisterCommands()
{
LoginCommand?
.Configure(
execute: (msg) => { Login(User); },
canExecute: (x) => { return CanLogin(); }
);
}
and call it when class is instantiated, but i don't want call this method in every derived class constructor (if I have 100 derived classes I must call RegisterCommand 100 times).
Normal solution is call RegisterCommand in the base class constructor
protected abstract void RegisterCommands();
public ViewModelBase()
{
RegisterCommands();
}
and this usually works (even if I do not know if it's a good practice) but...but...
in my scenario, in all the RegisterCommands methods I use my ICustomCommand objects, which are initialized in the derived class constructor with dependency injection
public class LoginViewModel : ViewModelBase
{
private ICustomCommand _loginCommand;
public ICustomCommand LoginCommand
{
get
{
return _loginCommand;
}
set
{
_loginCommand = value;
}
}
public LoginViewModel(ICustomCommand loginCommand)
{
_loginCommand = loginCommand;
}
protected override void RegisterCommands()
{
LoginCommand?
.Configure(
execute: (msg) => { Login(User); },
canExecute: (x) => { return CanLogin(); }
);
}
So, because base class constructor is called before derived class constructor, I can't call RegisterCommands() in base class constructor (because my ICustomCommands are not initialized yet in derived class so RegisterCommands() try to use my ICustomCommand which are still null).
I know that is not possible call derived class constructor before base class constructor, so what could be a valid, simple and clean solution to call RegisterCommands in all derived class calling this command in only one point?
thanks for answer
UPDATE:
As I said, RegisterCommands() is plural because every derived class could have N ICustomCommand objects
So I can have
LoginCommand for my LoginViewModel
SaveCommand, DeleteCommand for another ViewModel
etc.
One solution I think now is to remove ICustomCommand initialization from constructor and resolve it "on the fly" in getter property trough a static Resolver class, something like this
public ICustomCommand LoginCommand
{
get
{
if(_loginCommand == null)
MyStaticResolver.Resolve<ICustomCommand>();
return _loginCommand;
But I'm still not convinced