Из "Перечисления 7-7, Добавляющего Метод Действия"
на странице 165 книги
когда я добавляю
"Вид возврата (репозиторий. Продукты);"
я получил
Ошибка: свойство или индексатор 'SportsStore.Domain.Abstract.IProductRepository.Products' нельзя использовать в этом контексте, так как метод доступа get недоступен.
И тогда, когда я пытаюсь бежать - я получаю
«Непоследовательная доступность: тип свойства« System.Linq.IQueryable »менее доступен, чем свойство« SportsStore.Domain.Abstract.IProductRepository.Products »
Я просто пытаюсь добраться до пункта в первом разделе главы 7, где метод действия основан на фиктивной реализации интерфейса репозитория, который генерирует некоторые простые тестовые данные.
Вот мой код
NinjectControllerFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
namespace WebUI.Infrastructure
{
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
// put additional bindings here
// Mock implementation of the IProductRepository Interface
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(mock => m.Products).Returns(new List<Product> {
new Product { Name = "Football", Price = 25 },
new Product { Name = "Surf board", Price = 179 },
new Product { Name = "Running shoes", Price = 95 }}.AsQueryable());
ninjectKernel.Bind<IProductRepository>().ToConstant(mock.Object);
}
}
}
Global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System
.Web.Routing;
using WebUI.Infrastructure;
namespace WebUI
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Product", action = "List", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
}
}
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SportsStore.Domain.Entities
{
class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
}
IProductRepository.cs
using System.Linq;
using SportsStore.Domain.Entities;
namespace SportsStore.Domain.Abstract
{
public interface IProductRepository
{
IQueryable<Product> Products { get; }
}
}
ProuctController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
namespace WebUI.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
private IProductRepository repository;
public ProductController(IProductRepository productRepository){
repository = productRepository;
}
public ViewResult List() {
return View(repository.Products);
}
}
}
List.cshtml
@model IEnumerable<SportsStore.Domain.Entities.Product>
@{
ViewBag.Title = "Products";
}
@foreach (var p in Model)
{
<div class= "item">
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
Assemblyinfo.cs
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Domain")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Domain")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
IProductRepository.cs
using System.Linq;
using SportsStore.Domain.Entities;
namespace SportsStore.Domain.Abstract
{
public interface IProductRepository
{
IQueryable<Product> Products { get; }
}
}