✅ Which is the more correct way of class instantiation?
Is it better to instantiate your used objects like this in the
app.axaml.cs
file and then pass them off to the main window view model like the public override function at the top or is it better to instantiate your used objects in the main window view model like the code block underneath it? I ask because I've noticed that when I build a new view model, if I instantiate the items I need right there in the class as new instances of that item, I don't have the need for two constructors like
so I'm just curious to if it's user preference, or which is more correct12 Replies
Depends on a few things. First, the parameterless constructor implies that the helper object is optional
But it's not declared as such, so that's an orange flag.
However, beyond that it's really up to you if you want to do inversion of control or not
the only reason I have two constructors is because when I pass variables from the previous file to the next file, I get an error saying that the view model can't find a good enough constructor
I forgot to put the
: this()
on the one that is supposed to be calledTaking the dependency as a constructor parameter let's you easily use DI for example
But if you dont plan on using DI, there isn't much to win
DI means dependency injection, right?
Yup
so passing the instance from app.axaml.cs to MWVM is DI when I use that passed object in the MWVM
ok so I'm still not quite satisfied. Which is better? DI or new instantiations in each view model and other classes (creating multiple instances)?
Depends. Does the helper class have internal state that shouldn't be mixed across multiple windows?
If it does, don't inject the same instance
If it doesn't, can the helper be static?
this is one of my helper files. The other one is a JsonEngine which is a public class with internal functions
This one seems as if it could be static, techically
but if we disregard that and speak about the concept generally, I'd usually recommend passing them in via the constructor, as it gives more freedom
you can tweak what VMs share what dependencies as you need - new every time, partial sharing, full sharing, etc
gotcha. thanks!
just to be sure I understand the lingo.
This one seems as if it could be static, technicallyright?
Yeah, pretty much
ok bet. ty