How do I inject dependencies to user controls in W

2019-02-08 14:01发布

问题:

What is the best way to transparently inject dependencies (using IOC container) to user controls in WPF?

I assume that user controls are part of XAML for the window or other user controls. Also I think parent (whoever it is) should not be responsible for this. Solution for manually injecting dependencies from parent looks not clean enough for me. I want to avoid managing the dependencies of my components explicitly as it voilates the idea of IOC.

Is any event which is raised when logical tree is being created so I can intercept it and inject my dependencies?

EDIT: by dependencies I also mean ViewModel, Controller, Presenter (whatever pattern is used)

Thanks, Andrey

回答1:

The best way to deal with dependencies in WPF is by following the MVVM pattern.

In short, you don't inject dependencies directly into User Controls (View), but rather into their DataContext (ViewModel).



回答2:

The way i did it is to have an overall application class which injects dependencies into your viewmodel class (assuming your using MVVM design pattern ?) - use a DI container like Unity. See the WPF Application Framework (http://waf.codeplex.com/) which contains samples of just such a scenario that you're describing.



回答3:

FrameworkElement has an Initialized event, which you could hook up and inject the dependencies. You should test if it comes early enough for your scenario.



回答4:

I struggled with this mind block too:

Also I think parent (whoever it is) should not be responsible for this.

Then who will? The point of IoC is that something else (parent, view model, something, ...) defines the dependencies.



回答5:

One of the possible ways to solve the problem is to go with "ViewModel First" approach and using convention over configuration.