JustinN
JustinN

Reputation: 926

Binding two separate instances of an interface into an object constructor

I have the following interfaces and objects

public interface IFoo{}
public interface IBar{}

public class Foo : IFoo {
    public Foo(IBar bar1, IBar bar2)
    {
    }
}

public class Bar1 : IBar {}
public class Bar2 : IBar {}

and I have the following Ninject bindings

Bind<IBar>()
    .To<Bar1>()
    .InSingletonScope()
    .Named("bar1");
Bind<IBar>()
    .To<Bar2>()
    .InSingletonScope()
    .Named("bar2);
Bind<IFoo>()
    .To<Foo>()
    .InSingletonScope()
    .WithConstructorArgument("bar1", context => Kernel.Get<IBar>("bar1"))
    .WithConstructorArgument("bar2", context => Kernel.Get<IBar>("bar2"));

Now this works, however I really do not like having to specify the constructor values to the class of 'Foo' manually. Ideally, I would like something that allowed me to say this:

All constructor properties that have the property name of 'bar1' should use the named instance of the same name, and if the named instance does not exist, then use the default instance of 'Bar2'

Or something along those lines.

So really, is there a better way of doing what I am trying to achieve?

Upvotes: 0

Views: 128

Answers (1)

Trevor Pilley
Trevor Pilley

Reputation: 16393

Instead of having named instances, just change the constructor to be

public class Foo : IFoo 
{
    public Foo(IBar[] bars)
    {
    }
}

Then Ninject will inject an instance of each type of IBar registered.

Upvotes: 1

Related Questions