使用 BindDefaultInterface 时 MVC Ninject 绑定错误

MVC Ninject binding error when using BindDefaultInterface

我正在学习单元 testing/dependency injection/mocking。使用 Ninject,我可以将接口绑定到实现,如下所示 NinjectWebCommon.cs:

kernel.Bind<IRecipeRepository>().To<RecipeRepository>();

这很好用。但是,我不想将每个接口单独绑定到具体实现。为了克服这个问题,我使用了接口的标准命名约定(IFoo 是 class Foo 的接口),并尝试使用以下内容为所有接口提供默认绑定 Ninject.Extensions.Conventions。注意:此代码位于 NinjectWebCommon.cs:

中的 CreateKernel() 方法中
kernel.Bind(c => c
        .FromThisAssembly()
        .IncludingNonePublicTypes()
        .SelectAllClasses()
        .BindDefaultInterface()
        .Configure(y => y.InRequestScope()));

但是,当我这样做时,我收到以下错误:

Error activating IRecipeRepository
No matching bindings are available, and the type is not self-bindable.
Activation path:
 2) Injection of dependency IRecipeRepository into parameter recipeRepository of constructor of type RecipesController
 1) Request for RecipesController

感谢所有帮助。

编辑:我的控制器的构造函数如下所示:

    private IRecipeRepository recipeRepository;
    private ISizeRepository sizeRepository;

    [Inject]
    public RecipesController(IRecipeRepository recipeRepository, ISizeRepository sizeRepository)
    {
      this.recipeRepository = recipeRepository;
      this.sizeRepository = sizeRepository;
    }

无法将 IRecipeRepository 绑定到 RecipeRepository 的原因是它们与控制器位于不同的程序集中。要解决您的问题,您必须在 NinjectWebCommon.cs 中添加另一个绑定。这仅在接口和具体 类 位于同一程序集中时有效:

kernel.Bind(c => c
                .FromAssemblyContaining<IRecipeRepository>()
                .IncludingNonePublicTypes()
                .SelectAllClasses()
                .BindDefaultInterface()
                .Configure(y => y.InRequestScope()));

如果具体的实现和接口在不同的项目中,您应该将 .FromAssemblyContaining<IRecipeRepository>() 替换为 .FromAssemblyContaining<RecipeRepository>(),并且应该会很有魅力。