Unclear how to implement dependency injection

Let's say I have a LoginView and its data context, LoginViewModel, needs to be injected with a service that can authenticate a user based on their username / password.

Now let's say that the state of the application is that someone is already logged in, but now they are logging out and I need to re-display the login screen for the next user. So at this point I need an instance of my LoginViewModel, but I'm not sure how to get it.

Do I have to inject LoginViewModel into my ShellViewModel and hold and reuse it? This seems odd because I would like to keep this in memory until I use it (provided, but not very important in this case, but could be for other cases as well).

Do I have to inject the authentication service into the ShellViewModel to hold when needed to create the LoginViewModel? This seems odd because my ShellViewModel doesn't need to do anything with this service, and if that were the answer, I would inject all my stuff into my ShellViewModel for all the other ViewModels it displays.

And I know that I shouldn't reference my DI container anywhere other than the root of my application, or I will use the Locator pattern.

Admittedly, I feel pretty stupid right now, and I'm sure I'm going to punch myself in the face when I hear the answer ... so what is it?

+2


source to share


2 answers


In a scenario like this, I usually add what will match the LoginViewModel factory in your case. This way, your logic can create a new one as needed (or possibly cached by the factory instance).



+1


source


After not searching various blogs, Q&A on this topic for the past few hours, I am starting to conclude that a framework like Asp.net MVC makes a purist implementation (aka someone like Mark Semann) fit quite feasibly.

Structures like this tend to make this possible because the structure itself uses a template (Locator) for service (gasp !!!). Unfortunately, using MVVM design on a platform like WPF does not make it quite as easy due to the fact that your views are not always served from the root using the built-in service locator.



I do, however, have a ShellViewModel that is responsible for displaying most of the views I want, and so I find the most practical answer here is to consider my ShellViewModel as part of the composition root and extend my dependency on the DI container into it.

Apart from the point of my ShellViewModel though, I believe the 500 answer is correct.

+1


source







All Articles