Enabling DI for WPF UserControl (or any class for that matter) #745
Closed
nicolaihenriksen
started this conversation in
Ideas
Replies: 1 comment
-
Converted this into a feature request issue #746 so I am closing this discussion topic. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
The text below is copied from my repository README.md where I have built a proof-of-concept implementation of this feature.
The problem described below is probably the most compelling use case for this feature, however I do see other use cases for it as well.
Consider a simple WPF application using the
GenericHost
to enable dependency injection following the standard .NET scheme.The approach is nicely described in this video by @keboo.
This allows us to extract the "top-most" view from the DI container (and thus use a non-default constructor). However, nested controls inside this view are problematic, because they are "instantiated by the XAML parser" and thus require an empty default constructor.
Consider a "top-most" view called
MainWindow
using aUserControl
(or a custom control):MainWindow.xaml
We now want the nested view (i.e.
MyUserControl
) to have a non-default constructor so we can use dependency injection:MyUserControl.xaml.cs (code-behind)
As mentioned, this will not work out of the box, because there needs to be an empty default constructor.
This is just one example of the issue. I could easily imagine other scenarios where this could be useful. For example a "plugin architecture" scenario where plugins are instantiated via reflection using the default constructor.
Proposed solution
The general idea is quite simple:
For this to work, basically 2 things are needed:
IServiceProvider
from the generated constructors in order to lookup the required services.Desired usage
I want the usage of this to be as simple as possible. Hopefully only 2 steps are needed:
MyUserControl
) which should be "DI-enabled" with a marker attribute.IHostBuilder
using a simple extension method.Ideally something like this:
Beta Was this translation helpful? Give feedback.
All reactions