Prism WPF - How to access ServiceLocator inside UserControls or Custom Controls

1.1k Views Asked by At

I have some reusable UserControls, inside those UserControls i want to access some service instances which i registered inside bootstrapper.

I cannot do constructor injection because those user controls are used directly inside xaml, so i tried to access ServiceLocator.Current but it threw exception.

So what is the best practice for accessing registered service instances inside user controls which you cannot do constructor injection as WPF wants parameterless constructor to load them inside xaml.

(Btw, I am using UnityBootstrapper)

1

There are 1 best solutions below

6
On

You can create a DependencyProperty IUnityContainer and you give your control an instance to it in xaml:

<local:MyControl UnityContainer="{Binding Container}"/>

Now you can access it inside the MyControl. Will this do?

My team likes to use a static reference to the container, but we are allowed to use it only inside converters. Perhaps you could use that too in this case:

<local:MyControl UnityContainer="{UnityContainer}"/>

This is what you need to make this option work:

public static class MarkupExtensionHost
{
    public static IUnityContainer Container { get; set; }
}

public class UnityContainerExtension : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return MarkupExtensionHost.Container;
    }
}