Open nicolaihenriksen opened 1 year ago
yes, that's easy to use,
now , we must define a Func or Action Dependency Property in the user control,
inject the the IService in the window of control's parents ,
assign the Action or Func which to use IService.
then binding it to the xaml. it's too complex.
other solution, use the inject tool support property inject or method inject
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: