Dependency Injection in XAML (WPF)
I am creating a new WPF project and we use Microsoft Unity as DI.
I am having a user control which is calling a 3rd party service.
So now how to inject dependency from the main window XAML for the usercontrol.
You can use the service locator pattern. I use it with Unity as a DI.
internal class ServiceLocator
{
[...]
public MainViewModel Main { get { return container.Resolve<MainViewModel>(); } }
}
You can intantiate your class the way you want (DI or not, the class initializes the DI etc...).
In your App.xaml
<Application.Resources>
<vm:ServiceLocator x:Key="Locator"/>
</Application.Resources>
And now, you can set your datacontext
DataContext="{Binding Main, Source={StaticResource Locator}}"
Edit:
I found another way of doing it (among other): Take a look at this article. In the command, you can resolve your viewmodel as you like.
精彩评论