【发布时间】:2021-04-29 09:06:09
【问题描述】:
我是 c# 和 asp.net 核心的新手,我按照一些教程进行操作,但在访问餐厅页面时出现此错误: “InvalidOperationException:尝试激活‘OdeToFood.Pages.Restaurants.ListModel’时无法解析‘Data.IRestaurantsData’类型的服务”
Restaurant.cs
namespace Core
{
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public CuisineType Cuisine { get; set; }
}
}
IRestaurantsData.cs
namespace Data
{
public interface IRestaurantsData
{
IEnumerable<Restaurant> GetAll();
}
public class InMemoryRestaurantsData : IRestaurantsData
{
public List<Restaurant> restaurants;
public InMemoryRestaurantsData()
{
restaurants = new List<Restaurant>()
{
new Restaurant { Id = 1, Name = "Pizza", Location = "Milano", Cuisine = CuisineType.Italian },
new Restaurant { Id = 2, Name = "Rice", Location = "Mexic", Cuisine = CuisineType.Mexican },
new Restaurant { Id = 3, Name = "Chicken", Location = "london", Cuisine = CuisineType.Indian},
};
}
public IEnumerable<Restaurant> GetAll()
{
return from r in restaurants
orderby r.Name
select r;
}
}
}
List.cshtml
namespace OdeToFood.Pages.Restaurants
{
public class ListModel : PageModel
{
private readonly IRestaurantsData _restaurantsData;
public IEnumerable<Restaurant> Restaurants;
public ListModel(IRestaurantsData restaurantsData)
{
this._restaurantsData = restaurantsData;
}
public void OnGet()
{
Restaurants = _restaurantsData.GetAll();
}
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Data;
namespace OdeToFood
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
services.AddSingleton<IRestaurantsData, InMemoryRestaurantsData>();
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
}
}
我只是想知道哪里出了问题以及为什么。谢谢
【问题讨论】:
标签: c# asp.net-core dependency-injection