Thomas Wormald
Thomas Wormald

Reputation: 187

Nested Generics and Dependency Injection C#

I'm relatively new to dependency injection. I think I get the idea, but I'm now presented with this problem. Assume that I have some interfaces and some classes:

interface IA<T>
interface IB<IA<T>>
class A<T> : IA<T>
class B<IA<T>> : IB<IA<T>>

I want to register the following in my dependency injection container:

container.Register<IB<IA<T>>, B<A<T>>(...);

When I try to resolve IB<IA<T>>, it fails with an exception explaining that IB<IA<T>> cannot be converted to B<A<T>>.

Why did it fail, and how can I fix it?

Upvotes: 1

Views: 721

Answers (1)

SKall
SKall

Reputation: 5234

Like Alexei posted already you wouldn't use generics that way. You would probably want something like this instead:

public interface IA<T>
{
    T Item { get; }
}

public interface IB<T>
{
    IA<T> IA { get; }
}

Sample implementations:

public class A<T> : IA<T> 
{
    public T Item
    {
        get;
        set;
    }
}

public class B<T> : IB<T>
{
    public B(IA<T> ia)
    {
        this.IA = ia;
    }

    public IA<T> IA
    {
        get;
        private set;
    }
}

Since the subject is dependency injection notice the B implementation does not have parameterless constructor. Instead it notifies its dependency in the constructor.

Setting up the container, first register IA implementation:

        container.Register<IA<int>, A<int>>(); // specific implementation or
        container.Register(typeof(IA<>), typeof(A<>)); // generic registration

Registering IB would be the same and the container should take care of injecting the dependency to class B's constructor:

        container.Register<IB<int>, B<int>>();
        container.Register(typeof(IB<>), typeof(B<>));

Resolving at runtime you would need to specify the type:

        var intIB = container.Resolve<IB<int>>();
        var stringIB = container.Resolve<IB<string>>();

Upvotes: 1

Related Questions