使用Ninject将超级接口绑定到子接口

时间:2012-11-02 18:12:17

标签: c# ninject

此代码不起作用。我基本上有一些超级接口和子接口的实现。我希望超级接口返回所有实现,子接口只返回子实现。我不想明确地将子实现绑定到子接口和超级接口。我想将它绑定到子接口,并以某种方式将sub绑定到super。我试图像这样设置它,但它不起作用:

class Program
{
    static void Main(string[] args)
    {
        IKernel kernel = new StandardKernel();
        kernel.Bind<ISuperInterface>().To<ISubInterface>(); // What can I do instead of this?
        kernel.Bind<ISuperInterface>().To<SuperImplementation>();
        kernel.Bind<ISubInterface>().To<SubImplementation>();

        var subs = kernel.GetAll<ISubInterface>(); // I want this to return a SubImplementation
        var supers = kernel.GetAll<ISuperInterface>(); // I want this to return a SuperImplementation and a SubImplementation

        Console.WriteLine(subs.Count());
        Console.WriteLine(supers.Count());
    }
}

public class SubImplementation : ISubInterface
{
}

public class SuperImplementation : ISuperInterface
{
}

public interface ISuperInterface
{
}

public interface ISubInterface : ISuperInterface
{
}

1 个答案:

答案 0 :(得分:0)

Ninject支持接口分离:

kernel.Bind<ISuperInterface>().To<SuperImplementation>();
kernel.Bind<ISuperInterface, ISubInterface>().To<SubImplementation>();

如果您使用的是约定,则可以使用BindAlInterfaces