我正在使用API来实现某些服务。
我收到错误:
InvalidOperationException:尝试激活“Zipcode_Service.Controllers.CityController”时,无法解析类型“Zipcode_Service.Models.IZipcodeRepository”的服务。
我的cotroller的构造函数或_repository的减速导致了这个问题:
private IZipcodeRepository _repository;
public CityController(ILogger<CityController> logger, IZipcodeRepository repository)
{
_logger = logger;
_repository = repository;
}
我的界面:
public interface IZipcodeRepository
{
IEnumerable<City> GetCitiesByCityName(string cityName);
// City GetCityNameById(int cityId);
}
我的ZipcodeRepository:
public class ZipcodeRepository : IZipcodeRepository
{
private ZipcodeContext _context;
private ILogger<ZipcodeRepository> _logger;
public ZipcodeRepository(ZipcodeContext context, ILogger<ZipcodeRepository> logger)
{
_context = context;
_logger = logger;
}
public IEnumerable<City> GetCitiesByCityName(string cityName)
{
return _context.Cities.Where(t => t.Name.Contains(cityName)).ToList();
}
我看到很多类似的问题,大多数人都提出问题出在控制器中,使用的是存储库,而不是接口。事实并非如此。
编辑:更多信息
我的启动页面:
public Startup(IHostingEnvironment env)
{
_env = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
_config = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddDbContext<ZipcodeContext>();
services.AddScoped<IZipcodeRepository, ZipcodeRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "App", action = "Index" }
);
我的上下文类:
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"]);
}
答案 0 :(得分:2)
当容器尝试解析对象图以满足依赖关系时,问题通常与错误相关。
您在评论中表明您注册了IZipcodeRepository
services.AddScoped<IZipcodeRepository, ZipcodeRepository>();
大。但是,在尝试初始化实现ZipcodeRepository
或其中一个依赖项时,也会发生该错误。例如,如果ZipcodeContext
在初始化时抛出异常,则会导致同样的问题。
确保上下文也已正确配置。
例如
services.AddDbContext<ZipcodeContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionNameHere")));