How do I inject dependencies to user controls in W

2019-02-08 13:37发布

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

5条回答
啃猪蹄的小仙女
2楼-- · 2019-02-08 13:50

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.

查看更多
爷的心禁止访问
3楼-- · 2019-02-08 13:50

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.

查看更多
别忘想泡老子
4楼-- · 2019-02-08 13:58

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).

查看更多
SAY GOODBYE
5楼-- · 2019-02-08 14:04

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

查看更多
\"骚年 ilove
6楼-- · 2019-02-08 14:08

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.

查看更多
登录 后发表回答