Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM-light There is already a factory registered for INavigationService

I'm trying to adjust my WP8 project from self made MVVM implementation to MVVM Light.

The application compiles without errors, but when I open my MainPage.xaml in Expression Blend, I will get this error:

Class project.Services.INavigationService is already registered. App.xaml

My ViewModelLocator.cs:

    /// <summary>
    /// Initializes a new instance of the ViewModelLocator class.
    /// </summary>
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        if (ViewModelBase.IsInDesignModeStatic)
        {

        }
        else
        {
            if (!SimpleIoc.Default.IsRegistered<INavigationService>())
            {
                SimpleIoc.Default.Register<INavigationService>(() => new NavigationService());
            }
        }

        SimpleIoc.Default.Register<MainPage>();
        SimpleIoc.Default.Register<SettingsEditViewModel>();
    }

As you can see from my code comment, I've already tried the fix supposed here, but I'm still getting this error in Blend. There is no other place left where I could register the INavigationService, so what could be the problem?

Any ideas? :)

like image 931
Mamamouchi Avatar asked Jul 11 '13 12:07

Mamamouchi


Video Answer


1 Answers

I had the same issue, and this seems to be a Visual Studio issue in combination with XAML-Designer, Static Factories/Locators and Design-Time creation of objects. However: The solutions were the following:

  1. Register without a factory (not recommended)

    SimpleIoc.Default.Register<INavigationService>();

  2. Or if you want to use a factory, unregister before registering the factory

    SimpleIoc.Default.Unregister<INavigationService>(); SimpleIoc.Default.Register<INavigationService>(() => new NavigationService());

  3. Prevent the ViewModelLocator from being created more than once by the designer/Blend by making the constructor static

    static ViewModelLocator() { ... }

The error is cumbersome but could happen in this scenario: You create objects during design-time (the ViewModelLocator within App.xaml probably) and whenever you change something in your Code, the Compiler is triggered and the ViewModelLocator gets re-created without ever unregistering the services. Therefore it will complain that in the factory has already been registered. In theory, when registering classes without factories multiple times, there should be an error as-well.

like image 56
Alexander Pacha Avatar answered Jan 31 '23 18:01

Alexander Pacha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!