Demarsch
Demarsch

Reputation: 1479

Resolution of type failed in child container but succeeded in parent container

I have Prism application with two modules where one (SecondModule) depends on another (FirstModule). I'm also using log4net and I would like to have separate logger for every module. Thus I try to user child containers. The SecondModule makes it this way

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 is a user control that is configured to auto-wire view model as its datasource and this viewmodel has contructor parameter IPatientSearchService. Now the problem is that when Prism tries to resolve IPatientSearchService during view-model auto-wiring it fails with exception

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

The thing is if I replace this.container = container.CreateChildContainer(); with this.container = container inside module contructor everything works fine. What is the problem with child container in this case?

EDIT: after some investigation I think I know the reason. The problem is that ViewModelLocator uses default container (which is parent container in my case) for resolving view-model. So new question is: how can I reconfigure it to use proper container?

Upvotes: 2

Views: 170

Answers (1)

user5420778
user5420778

Reputation:

Use the ViewModelLocationProvider.Register method. This lets you set up a mapping for any given view type to provide a factory method that constructs the appropriate ViewModel (such as using your child container).

Upvotes: 1

Related Questions