Search code examples
dependency-injectionprismdecoratorioc-container

Registering a decorated type in a Prism app DI container


I'm working on a WPF app using Prism with a DryIoc container. The Prism part is the only thing that should matter.

Let's say I have an interface and two classes, where one is decorating the other and they depend on another type ID that needs to be resolved by the container:

public interface IA {
    void Method();
}

public class A : IA {
    public A(ID d) { ... }
    public void Method() { ... }
}

public class B : IA {
    public B(ID d, IA a) { ... }
    public void Method() { ... }
}

How do I register this with IContainerRegistry so when I ask for an IA I get a B that's initialized with an A?

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.Register<ID, D>();
    containerRegistry.Register<IA, A>();
    containerRegistry.Register<IA, B>(); // ?
}

Solution

  • How do I register this with IContainerRegistry so when I ask for an IA I get a B that's initialized with an A?

    containerRegistry.Register<ID, D>();
    containerRegistry.Register<IA>( c => new B( c.Resolve<ID>(), c.Resolve<A>() ) );
    

    Yes, this is ugly and fragile. Therefore, I'd revisit the architecture and use generics to define the decorated type:

    public class B<DecoratedType> : IA where DecoratedType : IA
    {
        public B( ID d, DecoratedType a )
        {
        ...
        }
    }
    

    and

    containerRegistry.Register<IA,B<A>>();
    

    Disclaimer: I'm from an unity-background, and unity resolves concrete types without registration. If DryIOC doesn't do this, you have to add

    containerRegistry.Register<A>();