Search code examples
c#prismunity-containerioc-containerresolve

PRISM: RegisterType with name and ContainerControlledLifeTimeManager


I'm having a problem with this RegisterType.

container.RegisterType<IFoo, Foo>("Foo", new ContainerControlledLifetimeManager());

Each module I create it's gonna contain a similar the last register. Another modules would implement Foo2, Foo3 as the concrete type.

It's really necessary for me that contains the register type the name, because in external modules would invoke this object with the key.

The problem is also inside of the module, in its construtor needs IFoo as a parameter (as I know, to do this is necessary the object is ContainerControlledLifetimeManager), and when I set the function RequestNavigate and try to generate the viewModel:

public class FooViewModel
{
    // here cannot create the object.
    public FooViewModel(IFoo foo, ...)
    { .. }
}

And it throws:

ResolutionFailedException was unhandled by user code. Resolution of the dependency failed, type = "System.Object", name = "FooView". Exception ocurred while: while resolving. Exception is: InvalidOperation - The current type, Prism4Demo.ModuleA.IFoo, is an interface and cannot be constructed. Are you missing a type missing?


Solution

  • You can also use DependencyOverride during resolve

    container.Resolve<FooViewModel>(new DependencyOverride<IFoo>(container.Resolve<IFoo>("Foo")))
    

    Or ResolvedParameter during RegisterType.

    Update:

    container.RegisterType<FooViewModel>(
        new InjectionConstructor(new ResolvedParameter<IFoo>("Foo")));
    

    You can use Resolve even for View not for ViewModel only. It automaticly resolves dependency for ViewModel.

    regionManager.RegisterViewWithRegion(RegionNames.LeftRegion,
        () => this.container.Resolve<FooView>(new DependencyOverride<IFoo>
            (this.container.Resolve<IFoo>("Foo"))));