Feofilakt
Feofilakt

Reputation: 1388

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.

Upvotes: 0

Views: 46

Answers (1)

Jan Muncinsky
Jan Muncinsky

Reputation: 4408

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.

Upvotes: 1

Related Questions