Dependency Injection in XAML (WPF)

I am creating a new WPF project and we are using Microsoft Unity as a DI.

I have a user control that calls a third-party service.

So now, how to add a dependency from the main XAML window for usercontrol.

+3
source share
1 answer

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 may be interested in your class the way you want (DI or not, the class initializes 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:

( ): . , .

0

Source: https://habr.com/ru/post/1743969/


All Articles