如何使用带有 Prism 的 Unity 按约定注册类型?
How to register types by convention using Unity with Prism?
我有一个使用 Prism.Wpf
和 Prism.Unity
NuGet 包(两者都是 6.3.0
)的 WPF 应用程序。我目前正在引导程序 class(见下文)中手动在 Unity 容器中注册类型,并且一切正常。
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());
}
}
但是,当我尝试按照惯例注册类型时,在 Unity 容器中注册类型时得到 Microsoft.Practices.Unity.DuplicateTypeMappingException
。
注册约定代码:
protected override void ConfigureContainer()
{
base.ConfigureContainer();
// Register types by convention
Container.RegisterTypes(
AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default,
WithLifetime.ContainerControlled);
}
异常消息:
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.
使用 Prism & Unity 时如何按约定注册类型?
只需交换 Container.RegisterTypes(...);
和 base.ConfigureContainer();
UnityBootstrapper
只会注册以前没有注册的类型,所以你应该没问题。
我有一个使用 Prism.Wpf
和 Prism.Unity
NuGet 包(两者都是 6.3.0
)的 WPF 应用程序。我目前正在引导程序 class(见下文)中手动在 Unity 容器中注册类型,并且一切正常。
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());
}
}
但是,当我尝试按照惯例注册类型时,在 Unity 容器中注册类型时得到 Microsoft.Practices.Unity.DuplicateTypeMappingException
。
注册约定代码:
protected override void ConfigureContainer()
{
base.ConfigureContainer();
// Register types by convention
Container.RegisterTypes(
AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default,
WithLifetime.ContainerControlled);
}
异常消息:
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.
使用 Prism & Unity 时如何按约定注册类型?
只需交换 Container.RegisterTypes(...);
和 base.ConfigureContainer();
UnityBootstrapper
只会注册以前没有注册的类型,所以你应该没问题。