How can I bind the same dependency to many dependents in Ninject?

Posted by Mike Bantegui on Stack Overflow See other posts from Stack Overflow or by Mike Bantegui
Published on 2012-09-12T02:57:35Z Indexed on 2012/09/12 3:38 UTC
Read the original article Hit count: 114

Filed under:
|
|

Let's I have three interfaces: IFoo, IBar, IBaz. I also have the classes Foo, Bar, and Baz that are the respective implementations.

In the implementations, each depends on the interface IContainer. So for the Foo (and similarly for Bar and Baz) the implementation might read:

class Foo : IFoo
{
    private readonly IDependency Dependency;

    public Foo(IDependency dependency)
    {
           Dependency = dependency;
    }

    public void Execute()
    {
         Console.WriteLine("I'm using {0}", Dependency.Name);
    }
}

Let's furthermore say I have a class Container which happens to contain instances of the IFoo, IBar and IBaz:

class Container : IContainer
{
    private readonly IFoo _Foo;
    private readonly IBar _Bar;
    private readonly IBaz _Baz;

    public Container(IFoo foo, IBar bar, IBaz baz)
    {
        _Foo = foo;
        _Bar = bar;
        _Baz = baz;
    }
}

In this scenario, I would like the implementation class Container to bind against IContainer with the constraint that the IDependency that gets injected into IFoo, IBar, and IBaz be the same for all three. In the manual way, I might implement it as:

IDependency dependency = new Dependency();
IFoo foo = new Foo(dependency);
IBar bar = new Bar(dependency);
IBaz baz = new Baz(dependency);
IContainer container = new Container(foo, bar, baz);

How can I achieve this within Ninject?

Note: I am not asking how to do nested dependencies. My question is how I can guarantee that a given dependency is the same among a collection of objects within a materialized service.

To be extremely explicit, I understand that Ninject in it's standard form will generate code that is equivalent to the following:

IContainer container = new Container(new Foo(new Dependency()), new Bar(new Dependency()), new Baz(new Dependency()));

I would not like that behavior.

© Stack Overflow or respective owner

Related posts about c#

Related posts about dependency-injection