简体   繁体   English

NInject为每个类型参数的实现实现绑定通用接口

[英]NInject binding generic interface to its implementations for each type parameter

I bind generic interface to its implementations: 我将通用接口绑定到其实现:

class Program
{
    static void Main(string[] args)
    {
        IKernel kernel = new StandardKernel();

        kernel.Bind<ICreator<bool>>().To<BoolCreator>().InSingletonScope();
        kernel.Bind<ICreator<int>>().To<IntCreator>().InSingletonScope();
        kernel.Bind<ICreator<string>>().To<StringCreator>().InSingletonScope();

        Console.WriteLine(kernel.Get<ICreator<bool>>().Create());
        Console.WriteLine(kernel.Get<ICreator<int>>().Create());
        Console.WriteLine(kernel.Get<ICreator<string>>().Create());
    }
}

interface ICreator<T>
{
    T Create();
}

class BoolCreator : ICreator<bool>
{
    public bool Create() => true;
}

class IntCreator : ICreator<int>
{
    public int Create() => 123;
}

class StringCreator : ICreator<string>
{
    public string Create() => "abc";
}

When a new class is added, it also have to be binded manually. 添加新类时,还必须手动绑定。 Is there way to bind it automatically? 有没有办法自动绑定它? I tried this: 我尝试了这个:

        kernel.Bind(scanner => scanner
            .FromThisAssembly()
            .SelectAllClasses()
            .InheritedFrom(typeof(ICreator<>))
            .BindSingleInterface()
            .Configure(b => b.InSingletonScope()));

but is does not work. 但是是行不通的。

Thanks. 谢谢。

Convention based binding works only on types that are public. 基于约定的绑定仅适用于公共类型。 Your types are by default internal as they have no access modifier. 您的类型默认为内部类型,因为它们没有访问修饰符。 Make them public and your binding will work. 将它们公开,您的绑定将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM