Cannot get Ninject.Extensions.Conventions to work

时间秒杀一切 提交于 2019-12-31 02:01:09

问题


I've been trying to get Ninject.Extensions.Conventions for (Ninject 3+) working, with no luck. I boiled it down to a found sample console app, and I can't even get that going. Here's what I have:

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

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

            var service = kernel.Get<Service>();
            service.OutputToConsole();

            Console.ReadLine();
        }

        public interface IConsoleOutput
        {
            void HelloWorld();
        }

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

        public class Service
        {
            private readonly IConsoleOutput _output;
            public Service(IConsoleOutput output)
            {
                _output = output;
            }

            public void OutputToConsole()
            {
                _output.HelloWorld();
            }
        }
    }

I've also tried various combos of FromAssembliesMatching, SelectAllTypes, BindDefaultInterfaces, etc. Everything throws the Error activating . No matching bindings are available, and the type is not self-bindable.

Just for sanity, if I do a manual binding with:

kernel.Bind<IConsoleOutput>().To<ConsoleOutput>();

Everything works just fine. So clearly I'm just missing something.


回答1:


It is caused, as sam suggested, by the types not being public. They are inner types of the non-public "Program" class.

Make Program public or add .IncludingNonPublicTypes():

kernel.Bind(x => x
    .FromThisAssembly()
    .IncludingNonPublicTypes()
    .SelectAllClasses()
    .BindAllInterfaces());

(I have verified that either works, and your code doesn't).

And here is your official source: https://github.com/ninject/ninject.extensions.conventions/blob/master/src/Ninject.Extensions.Conventions.Test/IntegrationTests/NonPublicTypesTests.cs

Note: In older versions of Ninject this method was called IncludeNonePublicTypes (None vs Non).



来源:https://stackoverflow.com/questions/18793095/cannot-get-ninject-extensions-conventions-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!