Binding generic type definitions with Ninject

A few days ago I came across a feature of Ninject that I didn’t know of: bindings of generic type definitions. Suppose you have a generic thing interface:

    interface IThing<T>
    {
        void DoSomething(T obj);
    }

A possible implementation is a console-based thing:

    class ConsoleThing<T> : IThing<T>
    {
        public void DoSomething(T obj)
        {
            Console.WriteLine("ConsoleThing<{0}>: {1}", typeof(T).Name, obj.ToString());
        }
    }

Ninject allows you to bind all the specific things to the corresponding console things by using their generic type definitions:

kernel.Bind(typeof(IThing<>)).To(typeof(ConsoleThing<>));

In this case we can’t use the generic overload of the Bind method because we are not specifying the thing‘s type arguments. Having that single bind you can write:

var intThing = kernel.Get<IThing<int>>();
var stringThing = kernel.Get<IThing<string>>();

intThing.DoSomething(1234);
stringThing.DoSomething("Hello");

And you can still have other dependencies, as usual, even if the use the generic type argument:

class SpecialThing<T> : IThing<T>
{
    private readonly T _obj;
    public SpecialThing(T obj)
    {
        _obj = obj;
    }

    public void DoSomething(T obj)
    {
        Console.WriteLine(_obj.Equals(obj));
    }
}
kernel.Bind(typeof(IThing<>)).To(typeof(SpecialThing<>));
kernel.Bind<string>().ToConstant("Foo");

var specialStringThing = kernel.Get<IThing<string>>();
specialStringThing.DoSomething("Hello"); // 'False'
specialStringThing.DoSomething("Foo"); // 'True'

Cool, rigth? May be useful in some scenarios, specially when combined with restrictions over the type arguments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s