没有匹配的绑定可用,并且类型不能自绑定.激活IProductsRepository时出错
本文关键字:绑定 类型 不能 激活 出错 IProductsRepository | 更新日期: 2023-09-27 18:14:09
我正在尝试学习MVC,我开始与书Pro ASP。. NET MVC由Adam Freeman编写(第5版@2013)。
在第七章中,我试图按照书中的例子制作一个小应用程序。
应用程序在设置并尝试加载产品列表后加载失败。
我试图创建抽象存储库IProductRepository的模拟实现,并有Ninject返回模拟对象,每当它得到一个请求的实现IProductRepository接口。
我已经搜索和查看了其他问题/答案,没有发现任何可以帮助解决我的问题,让我继续学习。这可能是基本的东西,但我真的想知道什么和为什么不工作,因为它应该。
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
}
}
下面是我的NinjectDependencyResolver类:
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
[Inject]
public NinjectDependencyResolver(IKernel kernelParam)
{
kernel = kernelParam;
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
var mock = new Mock<IProductsRepository>();
mock.Setup(m => m.Products).Returns(new List<Product>
{
new Product { Name = "Fotball", Price = 25 },
new Product { Name = "Surf Board", Price = 45 },
new Product { Name = "Running Shoes", Price = 95 }
});
kernel.Bind<IProductsRepository>().ToConstant(mock.Object);
}
}
这是我的控制器类
public class ProductController : Controller
{
private IProductsRepository repository;
public ProductController(IProductsRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Products);
}
我得到的错误如下:
激活IProductsRepository出错
没有匹配的绑定可用,并且类型不能自绑定。
激活路径:
2)将依赖IProductsRepository注入到ProductController类型的构造函数的参数productrerepository中。
1)请求ProductController.
建议:
1)确保你已经为IProductsRepository定义了绑定。2)如果绑定是在模块中定义的,确保该模块已经加载到内核中。
3)确保您没有意外创建多个内核。
4)如果使用构造函数实参,请确保形参名称与构造函数的形参名称匹配。
5)如果您使用自动模块加载,请确保搜索路径和过滤器是正确的。
好的,看来我有另一个错误说:
发现无法解决的同一从属程序集的不同版本之间的冲突
我已经安装了Ninject的特定版本,Ninject. web。常见,Ninject。MVC3、Moq和书籍作者指定的其他包。
在阅读构建输出中的错误后,我尝试将所有已安装的包更新到最新版本,重新构建项目,一切都工作得很好!