我一直在尝试让Ninject.Extensions.Conventions(适用于Ninject 3+)起作用,可是一直没有成功。 我将其简化为一个已找到的示例控制台应用程序,但是我甚至无法启动它。这是我的代码:
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();
}
}
}
我还尝试过各种组合使用FromAssembliesMatching、SelectAllTypes和BindDefaultInterfaces等方法,但是都会抛出“Error activating . No matching bindings are available, and the type is not self-bindable.”的错误提示。
为了保证正确性,如果我手动绑定如下内容:
kernel.Bind<IConsoleOutput>().To<ConsoleOutput>();
一切都很好。显然我只是漏了什么东西。