我一直在掙扎與此錯誤一會兒解析服務,不明白爲什麼:C#無法爲類型
無法解析服務類型「Microsoft.Extensions.Configuration.IConfigurationRoot」,而試圖激活'Zipcode_Service.Models.ZipcodeContext'。
我試圖尋找在連接被重新配置的所有地方,都顯得精緻:
ZipcodeContext:
public ZipcodeContext(IConfigurationRoot config, DbContextOptions options) : base(options)
{
_config = config;
}
public DbSet<City> Cities { get; set; }
public DbSet<Zipcode> Zipcodes { get; set; }
public DbSet<Street> Streets { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["ConnectionStrings:ZipcodeContextConnection"]);
}
ZipcodeController:
public class CityController : Controller
{
private ILogger<CityController> _logger;
private IZipcodeRepository _repository;
public CityController(ILogger<CityController> logger, IZipcodeRepository repository)
{
_logger = logger;
_repository = repository;
}
[HttpGet("{cityName}")]
public IActionResult GetCities(string cityName)
{
var results = _repository.GetCitiesByCityName(cityName);
return Ok(Mapper.Map<IEnumerable<CityViewModel>>(results));
}
ZipcodeRepository:
public class ZipcodeRepository : IZipcodeRepository
{
private ZipcodeContext _context;
public ZipcodeRepository(ZipcodeContext context)
{
_context = context;
}
public IEnumerable<City> GetCitiesByCityName(string cityName)
{
return _context.Cities.Where(t => t.Name.Contains(cityName)).ToList();
}
IZipcodeInterface:
public interface IZipcodeRepository
{
IEnumerable<City> GetCitiesByCityName(string cityName);
// City GetCityNameById(int cityId);
}
我啓動:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ZipcodeContext>();
services.AddScoped<IZipcodeRepository, ZipcodeRepository>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(_config.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "App", action = "Index" }
);
}
注:禁用CityController的構造和使用一個空的作品,我想誤差來源於_repository = repository
這是因爲你在'ZipcodeContext'中使用'IConfigurationRoot',我寧願推薦你使用[Options](https: //docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration#using-options-and-configuration-objects)模式。 –
它爲什麼重要?在接下來的教程中,他使用了IConfigurationRoot,並且該工作起作用。爲什麼現在不行? @YuriyN。 – sagi
您可以鏈接教程嗎?它現在不起作用,因爲在內置的Asp.Net Core依賴注入容器中,當DI面對它時,沒有註冊服務來解析'IConfigurationRoot'接口。 –