简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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