c# – 没有匹配的绑定可用,并且该类型不可自绑定.激活IProductsR
我正在尝试学习MVC,我开始使用Adam Freeman撰写的Pro ASP.NET MVC(第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时出错 解决方法
好的,所以似乎我有另一个错误说:
发现无法解析的同一依赖程序集的不同版本之间的冲突 我已经安装了Ninject,Ninject.Web.Common,Ninject.MVC3,Moq以及书籍作者指定的其他软件包的特定版本. 在阅读构建输出中的错误后,我尝试将所有已安装的软件包更新到最新版本,重建项目,一切正常! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |