Search code examples
c#.netinversion-of-controlninject

Ninject.Extensions.Conventions won't bind single interface


Can't get one of the samples from the Ninject.Extensions.Conventions Github page to work, version 3.3.0. BindDefaultInterface() works no problem, but BindSingleInterface(), as shown below, returns an exception of System.InvalidOperationException: 'Sequence contains no elements'.

I'm aware of the similarly titled SO question Cannot get Ninject.Extensions.Conventions to work. This is not the same (also, my Program class is public, which was the crux of that issue).

This is stripped down to as simple of a console app as we can get I think.

using System;
using Ninject;
using Ninject.Extensions.Conventions;

public class Program
{
    static void Main(string[] args)
    {
        var kernel = new StandardKernel();
        kernel.Bind(x => x
           .FromThisAssembly()
           .SelectAllClasses()
           .BindSingleInterface());

        var output = kernel.Get<IConsoleOutput>();
        output.HelloWorld();

        Console.ReadKey();
    }

    public interface IConsoleOutput
    {
        void HelloWorld();
    }

    public class ConsoleOutput : IConsoleOutput
    {
        public void HelloWorld()
        {
            Console.WriteLine("Hello world!");
        }
    }
}

Solution

  • Problem is, that Ninject tries to also bind your Program class, and because it doesn't implement any interface you get System.InvalidOperationException. If you add some dummy interface on Program class, your code will run without problems.

    But probably you should consider whether to use rather methods like BindDefaultInterfaceor BindAllInterfaces.