Ninject Dependency Injection and Mapping Open Generic Types as Singletons - Possible Bug

I provided an example of using Ninject for dependency injection of ASP.NET Web Pages similar to code and a screencast I did for Unity:

 

I think I found a bug in Ninject 1.0 that I will have to add to their bug list. This same bug was in Unity 1.0 before it was fixed in Unity 1.1.

In the Ninject example below, I am specifying that IValidator<T> binds to Validator<T> and I am telling it to use the SingletonBehavior. What this means to me is that Ninject will create a new singleton instance of Validator<T> for each IValidator<T> requested. Hence, there would be a Validator<int> singleton, Validator<string> singleton, etc.

Instead, Ninject 1.0 throw an InvalidCastException:

"Unable to cast object of type 'ConsoleApplication2.Validator`1[System.Int32]' to type 'ConsoleApplication2.IValidator`1[System.String]'." 

In the code shown below, a Validator<int> is first created and then when the request for an IValidator<string> is requested, Ninject tries to return the Validator<int> causing the exception. I wouldn't expect this.

 

using Ninject.Core;
using Ninject.Core.Behavior;

namespace ConsoleApplication2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IKernel kernel =
                new StandardKernel(new InfrastructureModule());
            IValidator<int> intValidator =
                kernel.Get<IValidator<int>>();
            IValidator<string> stringValidator =
                kernel.Get<IValidator<string>>();
        }
    }

    public class InfrastructureModule : StandardModule
    {
        public override void Load()
        {
            Bind(typeof (IValidator<>))
            .To(typeof (Validator<>))
            .Using<SingletonBehavior>();
        }
    }

    public interface IValidator<T>
    {
        void Validate(T obj);
    }

    public class Validator<T> : IValidator<T>
    {
        public void Validate(T obj)
        {
        }
    }
}

 

I use open generic types a lot in this scenario, so this is somewhat of a show-stopper for me at the moment. Of course, you could use TransientBehavior as a workaround until the “bug“ is fixed.

 

posted on Friday, June 20, 2008 2:55 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices