Ninject GetAll返回重复的对象

时间:2011-07-09 10:59:04

标签: ninject ninject-2

我有这段代码:

abstract class GenericAbstractClass<T> where T : struct { }

class ImplementationClass : GenericAbstractClass<int> { }

class Program {
    static void Main (string[] args)
    {
        IKernel kernel = new StandardKernel();
            kernel.Bind(typeof(GenericAbstractClass<>)).To(typeof(ImplementationClass));

            var classes = kernel.GetAll(typeof(GenericAbstractClass<>));
            Console.WriteLine(classes.Count()); // Print 2.

            foreach (var cls in classes) {
                if (cls is ImplementationClass)
                    Console.WriteLine("cls is ImplementationClass");
            }


            Console.ReadLine();
        }
    }

输出结果为:

2
cls is ImplementationClass
cls is ImplementationClass

我希望classes.Count()结果为1.

为什么GetAll会返回重复的对象,尽管我只将GenericClass绑定到ImplementationClass

如何让GetAll返回所有非重复对象?

P.S。我使用ninject 2.2

1 个答案:

答案 0 :(得分:3)

你的装订没有任何意义。您将开放的泛型类型绑定到已关闭的类型。似乎Ninject对绑定的合理性检查存在差距。

将绑定更改为

kernel.Bind(typeof(GenericAbstractClass<int>)).To(typeof(ImplementationClass));
kernel.GetAll(typeof(GenericAbstractClass<int>));