Why does ServiceLocator.Current.GetInstance cause UserControls to not work at design-time?

1.3k views Asked by At

I'm having an issue where if I call ServiceLocator.Current.GetInstance(type) anywhere in my project, it causes UserControls throughout my project to stop instantiating within other controls at design-time in Visual Studio. These controls work fine at run-time however.

It is reproducible by creating a simple WpfApplication with the following 3 classes. The first build will succeed, and the designer will show fine. If you rebuild, however, it throws the error and the designer stops instantiating the UserControls within other controls. Because of this behavior, it seems like a Visual Studio bug, but I'm not sure.

When uncommented, the #GetInstance(Type type) function of ServiceLocator causes an Error in the error list Cannot locate resource 'controls/test.xaml and the designer shows an error Cannot create an instance of "Test" where the Test UserControl should be. When commented, there are no errors.

Test xaml class.

<UserControl x:Class="XamlTest.Controls.Test"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d">
    <Grid>
        <Label Content="Test"/>
    </Grid>
</UserControl>

MyView xaml class. (uses Test)

<UserControl x:Class="XamlTest.Views.MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mycontrols="clr-namespace:XamlTest.Controls"
             mc:Ignorable="d">
    <Grid>
        <mycontrols:Test/>
    </Grid>
</UserControl>

A class unrelated to the UserControls that uses ServiceLocator.Current.GetInstance(type);.

using Microsoft.Practices.ServiceLocation;

namespace XamlTest.SomeClasses
{
    class SomeClass
    {
        public void SomeFunction()
        {
            // Causes Test xaml class to not instantiate at design time within MyView.
            // Does not matter what parameters you give the function.
            // Notice this class isn't even associated with any other class,
            //  and is never called, but it still causes problems.
            ServiceLocator.Current.GetInstance(null);
        }

    }
}
0

There are 0 answers