子容器中类型的解析失败但在父容器中成功

时间:2015-10-16 13:15:33

标签: c# unity-container prism ioc-container

我有两个模块的Prism应用程序,其中一个(SecondModule)依赖于另一个(FirstModule)。我也在使用log4net,我希望每个模块都有单独的记录器。因此,我尝试使用子容器。 SecondModule以这种方式实现

public class Module : IModule
{
    private readonly IUnityContainer container;

    private readonly IRegionManager regionManager;

    public Module(IUnityContainer container, IRegionManager regionManager)
    {
        this.regionManager = regionManager;
        this.container = container.CreateChildContainer();
    }

    public void Initialize()
    {
        RegisterServices();
        RegisterViews();
    }

    private void RegisterServices()
    {
        container.RegisterInstance(LogManager.GetLogger("PATSEARCH"));
        //register all other services
        container.RegisterType<IPatientSearchService, PatientSearchService>(new ContainerControlledLifetimeManager());
    }

    private void RegisterViews()
    {
        regionManager.RegisterViewWithRegion(RegionNames.MainMenu, () => container.Resolve<PatientSearch>());
        //register other views
    }
}

PatientSearch是一个用户控件,配置为将视图模型自动连接为其数据源,并且此视图模型具有构造函数参数IPatientSearchService。现在的问题是,当Prism在视图模型自动布线期间尝试解析IPatientSearchService时,它会失败并出现异常

The current type, PatientSearchModule.Services.IPatientSearchService, is an interface and cannot be constructed. Are you missing a type mapping?

问题是如果我在模块构造函数中用this.container = container.CreateChildContainer();替换this.container = container一切正常。在这种情况下,子容器有什么问题?

编辑:经过一番调查我觉得我知道原因。问题是ViewModelLocator使用默认容器(在我的情况下是父容器)来解析视图模型。所以新的问题是:如何重新配置​​它以使用合适的容器?

1 个答案:

答案 0 :(得分:1)

使用ViewModelLocationProvider.Register方法。这使您可以为任何给定的视图类型设置映射,以提供构造相应ViewModel的工厂方法(例如使用子容器)。