我正在尝试学习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时出错
没有匹配的绑定可用,并且该类型不可自绑定.
激活路径:
2)将依赖项IProductsRepository注入到ProductController类型的构造函数的参数productRepository中.
1)对ProductController的请求.
建议:
1)确保已为IProductsRepository定义了绑定.
2)如果在模块中定义了绑定,请确保已将模块加载到内核中.
3)确保您没有意外创建多个内核.
4)如果使用构造函数参数,请确保参数名称与构造函数参数名称匹配.
5)如果使用自动模块加载,请确保搜索路径和过滤器正确无误.
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。