Thoughts on Software by Andrew Davey
 Tuesday, April 29, 2008
Ninject Open Generic Types

I have started using Ninject a dependency injection framework for .NET. I find it very easy to use and recommend that people take a look.

Something in particular that I found useful is the ability to bind open generic types.

class Program
{
    static void Main(string[] args)
    {
        var k = new StandardKernel(new MyModule());

        var di = k.Get<Data<int>>();
        di.Content = 14;
        Console.WriteLine(di.Content);

        var ds = k.Get<Data<string>>();
        ds.Content = "hello";
        Console.WriteLine(ds.Content);
    }
}

class MyModule : StandardModule
{
    public override void Load()
    {
        Bind(typeof(IData<>)).To(typeof(Data<>));
    }
}

class Data<T> : IData<T>
{
    public T Content { get; set; }
}

interface IData<T>
{
    T Content { get; set; }
}

Very cool!


Tuesday, April 29, 2008 6:36:59 PM (GMT Standard Time, UTC+00:00)  #    Comments [1]   |  |  | 

Tuesday, April 29, 2008 7:44:56 PM (GMT Standard Time, UTC+00:00)
There one thousand and one of DI frameworks. Just anyone and his mom think it's a must to invent an DI nowadays.
Ray
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):