WPF MVVM and shared client classes.

Status
Not open for further replies.
Hi All,

I'm currently working on a WPF application utilizing MVVM pattern where my ViewModels contain the view logic for their respective view. I've come to a point, however; where I'm confused on what is considered best practice. In my case, I have a client class (Socket Client) which is accessed from various views and I'm not sure the best practice for locating references to this class. Currently I shoved it in the App.cs to make it accessible across all views/viewmodels, however; this seems akin to making it global and doesn't site well with me. So my first question is what is the best practice when sharing a client class across multiple Views (Pages/UserControls) and should my ViewModels be accessing that class for sending and receiving information?

Thanks in advance,
AimTron
 
I do have it separated in it's own assembly, however; I'm not sure if the class should become singleton (static) or a static reference in the app.cs so that multiple viewmodels can access it. I'm not sure of the best practices in this respect.

The other problem is that the viewmodels can't subscribe to the events until they're instantiated obviously, but the result of some events would logically result in the navigation to a page which results in the creation of the viewmodel. I'm wondering if I need a class in between that is managing the subscribed events and navigation events.
 

david_a

Ars Scholae Palatinae
819
Subscriptor++
The best practice is to inject a reference to it with a dependency injection framework. You would set up the registration in the framework to provide the correct object lifetime (IE return the same instance instead of creating new ones). The singleton pattern (with the static instance field) is an abomination that both makes testing a complete and utter pain and hides away your dependencies (because it's just a global variable with a fancier name).

Now, as for how to structure your app to use a DI framework, that's a completely different can of worms... I think some of the MVVM frameworks out there (Caliburn, MVVM Light, etc) follow this pattern in their templates.
 

krimhorn

Ars Legatus Legionis
39,865
[url=http:/civis/viewtopic.php?p=31729321#p31729321:147j5jzf said:
AimTron[/url]":147j5jzf]I do have it separated in it's own assembly, however; I'm not sure if the class should become singleton (static) or a static reference in the app.cs so that multiple viewmodels can access it. I'm not sure of the best practices in this respect.
Are you referring to a class that shares itself with many ViewModels? In what manner?

1: Are there simply methods that each ViewModel needs access to (and any resulting objects that are created are sent to the ViewModel and become detached from the method they were created in)?
2: Is the state of the class maintained/important (i.e. do you have properties/variables that can change/be changed by a user of the class)?
3: Is the class intended to only have a single instance?

In the case of 1: I'd take it static. It's, at that point, a helper class with shared functions. Note: the class should not have any properties in this case.

2: You have a regular class that needs to be instantiated for each ViewModel. Where you instantiate the ViewModels will determine where you instantiate this class. As david_a points out Dependency Injection is the current preference for doing this (constructor injection is the easiest).

3: This is the only time you'd go singleton but rule 1 of the singelton pattern: you don't need it 99% of the places where you think you do.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
The best practice is to inject a reference to it with a dependency injection framework. You would set up the registration in the framework to provide the correct object lifetime (IE return the same instance instead of creating new ones).

I would note that some would argue with the idea of the DI container being best practice.

Merely supplying the value directly passing it along as a constructor parameter rather than referencing it via a static variable may well be entirely sufficient... this is often called "Poor Man's DI" but is perfectly acceptable (both IMO and IME) unless you actually need more complex lifecycles than "there's just one"
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
I would agree.

For greenfield code, it's much better to simply "program to interfaces". Use DI patterns without a container.

There's a good argument to be made that DI containers are better if you're configuring by convention in order to support a plugin-style framework, but most applications should not involve a plugin framework.

But if your DI framework involves miles and miles and miles of configuration or in-line code at the entry point, then what is the container getting you?
 

david_a

Ars Scholae Palatinae
819
Subscriptor++
If you only have a few things to inject and you don't need to inject anything particularly deep into the tree, sure. If you suddenly have a need to inject something for an instance that is created like five levels deep you're going to be hurting without a real DI framework.

I think most modern DI frameworks have tools to automatically map Foo to IFoo out of the box. You should only need a lot of code to set up the container if you have complicated life cycles or need to have keyed lookups (IE tons of classes implementing IBar but you need to choose a particular one at construction time).

It also depends on how much you need to test things. I work on FDA regulated medical software so being able to thoroughly unit test classes is a requirement. Testing all the concrete classes together is handled by integration and verification tests.
 

TomXP411

Ars Tribunus Angusticlavius
9,356
[url=http:/civis/viewtopic.php?p=31729321#p31729321:3olsgecc said:
AimTron[/url]":3olsgecc]I do have it separated in it's own assembly, however; I'm not sure if the class should become singleton (static) or a static reference in the app.cs so that multiple viewmodels can access it. I'm not sure of the best practices in this respect.

The other problem is that the viewmodels can't subscribe to the events until they're instantiated obviously, but the result of some events would logically result in the navigation to a page which results in the creation of the viewmodel. I'm wondering if I need a class in between that is managing the subscribed events and navigation events.

Keep in mind that it's too easy to get bogged down in "which pattern should I use?" discussions. It's your program; implement this in the way that feels most organic to you. Remember what any program's goal is: it has to do what it's supposed to do. Worrying about this design pattern or that design pattern is like following fashion; what's popular today won't be in a week anyway, so just make a choice and go with it.

Now on the practical advice: The most flexible method is probably to pass a reference in via your view's constructors. You don't need to get fancy, but passing in the reference means that you can write unit tests with a test rig, and you can easily change and even re-implement your communications class without needing to change your views.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
no legacy code to work with (except perhaps in limited "call this function" sort of thing.

Trying to apply newer idioms to legacy code can be extremely hard (TDD is a bitch in many cases) without first spending a lot of time refactoring things, the worry there is that you are refactoring lots of code that likely has insufficient test coverage so it significantly increases risk.

The thing about containers I've recently realised (and made explicit by a wonderful talk linked in the perpetual thread) is that they make really complicated things really easy, but don't make it impossible/easy to spot when you screw up or want to change things. The former is fine when it's bullet proof, but isn't good otherwise.

In this hypothetical if you have a dependency on something five levels deep and no easy way to plumb it through that suggests that the wiring up of everything is screwed up. If you put everything together in one place (be it a composition root for a container, or simply by invoking constructors and passing the relevant instances about the complexity of the system should present itself clearly. That way you can either fix unnecessary complexity, or make it clear that really "Here be Dragons".

Your advice about "which pattern should I use" is entirely reasonable though, but I would argue that dropping in a container at this point would involve a lot of (possibly pointless) code rework. I would strive to get it to be done without one first, and only add the container once you know it will solve a specific problem. Using it as a shortcut to fixing some structural problem just papers over the problem.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
The thing about containers I've recently realised (and made explicit by a wonderful talk linked in the perpetual thread) is that they make really complicated things really easy, but don't make it impossible/easy to spot when you screw up or want to change things. The former is fine when it's bullet proof, but isn't good otherwise.

Yep. Same with ORMs. Every "powerful tool" you add is a trade off in productivity vs. understandability. In the case of ORMs and DI containers, any new engineer on the project has to not understand the concept of ORM/DI, but the ins and outs of the specific implementation you're using and the ins and outs of how you specifically used it.

Fewer lines of code is generally easier to understand, but does the productivity of the power tool you're using make up for the conceptual overhead it's adding?

In the case of DI, if you're starting with fresh code, you can go a long time with using "Poor Man's DI" without introducing a container framework. And you can always introduce the DI container later, if you need to.
 

david_a

Ars Scholae Palatinae
819
Subscriptor++
I just finished shoehorning a DI container into a 10 year old code base which obviously colors my responses. This experience certainly fuels my incredible hatred of the static singleton pattern which I think should be avoided at all costs. It's a global variable with a fancier name.

Also, all code becomes legacy code :)

But yeah, any sane DI system shouldn't ask you to structure your code any radically different than you would if were doing it manually. I used AutoFac for my recent effort which strives to introduce as little DI-specific stuff as possible in your code base (to various degrees of success).
 
Status
Not open for further replies.