Search code examples
c#wpfunity-containerprismprism-6

How to register types by convention using Unity with Prism?


I have a WPF app that uses the Prism.Wpf and Prism.Unity NuGet packages (both 6.3.0). I'm currently registering types in the Unity container manually in a bootstrapper class (see below) and everything is working great.

internal class Bootstrapper : UnityBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        return Container.Resolve<MainWindow>();
    }

    protected override void InitializeShell()
    {
        Application.Current.MainWindow.Show();
    }

    protected override void ConfigureContainer()
    {
        base.ConfigureContainer();

        // Register types
        Container.RegisterType<IDialogService, DialogService>(new ContainerControlledLifetimeManager());
    }
}

However, when I try to register types by convention, I get a Microsoft.Practices.Unity.DuplicateTypeMappingException when registering the types in the Unity container.

The register by convention code:

protected override void ConfigureContainer()
{
    base.ConfigureContainer();

    // Register types by convention
    Container.RegisterTypes(
        AllClasses.FromLoadedAssemblies(),
        WithMappings.FromMatchingInterface,
        WithName.Default,
        WithLifetime.ContainerControlled);
}

Exception message:

An attempt to override an existing mapping was detected for type Prism.Regions.IRegionNavigationContentLoader with name "", currently mapped to type Prism.Unity.Regions.UnityRegionNavigationContentLoader, to type Prism.Regions.RegionNavigationContentLoader.

How do I register types by convention when using Prism & Unity?


Solution

  • Just swap Container.RegisterTypes(...); and base.ConfigureContainer();

    The UnityBootstrapper will only register types that weren't registered before, so you should be fine.