【问题标题】:Resolution of type failed in child container but succeeded in parent container类型解析在子容器中失败,但在父容器中成功
【发布时间】:2016-01-15 06:22:56
【问题描述】:

我的 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 使用默认容器(在我的情况下是父容器)来解析视图模型。所以新的问题是:如何重新配置​​它以使用正确的容器?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-10-04
      • 2017-08-15
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多