0

I have a base class that implements an interface member as an abstract method. There are a few derived classes that override this abstract method. I have Ninject DI in place and Kernel will give an array of T(IEnumerable<T>). How can i call one specific derived class implementation using this IEnumerable<T>.

Here is some sample code

This is my interface

 public interface ICreateBatch
 {
    int CreateBatch();
 }

This is my base class with Interface implementation

public abstract class CreateBatchBase:ICreateBatch
{
    public abstract int CreateBatch();
}

Here is one of the derived class implementation

public class CreateDerived1Batch:CreateBatchBase
{
    public override int CreateBatch()
    {
        //Derived one implementation
    }
}

public class CreateDerived2Batch:CreateBatchBase
{
    public override int CreateBatch()
    {
        //Derived two implementation
    }
}

Ninject is giving me an IEnumerable. How can i specifically call CreateBatch() from CreateDerived1Batch?

Thanks in Advance.

Alberto
  • 15
  • 3
  • You should provide some code. – lucky Jan 22 '18 at 20:24
  • See [Dependency Injection Unity - Conditional resolving](https://stackoverflow.com/a/32415954/) and [Unity: Conditional resolving](https://stackoverflow.com/a/26608271/). Although these examples use Unity instead of Ninject, they are based on [design patterns](https://sourcemaking.com/design_patterns) so they will work with any DI container. – NightOwl888 Jan 23 '18 at 19:19

2 Answers2

2

I think the normal way in this case is to use contextual binding (see https://github.com/ninject/Ninject/wiki/Contextual-Binding). E.g. if you bind your interface like this:

kernel.Bind<ICreateBatch>().To<CreateDerived1Batch>().WhenInjectedInto(typeof(TypeDependingOn1);
kernel.Bind<ICreateBatch>().To<CreateDerived2Batch>().WhenInjectedInto(typeof(TypeDependingOn2);

the right ICreateBatch should be injected into TypeDependingOn1 and TypeDependingOn2respectively.

0

You can use LINQ extension method OfType<T> to filter only the items that are of a given type:

collection.OfType<Derived>().Method();
Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
  • As correct as the answer is, this goes against the principles of DI. You should not reference specific implementations outside of DI configuration. – jbl Jan 23 '18 at 12:52