ASP.NET Core error: System.InvalidOperationException: Unable to resolve service for type while attempting to activate
ASP.NET Core error: System.InvalidOperationException: Unable to resolve service for type while attempting to activate
我正在关注这篇文章:https://code-maze.com/net-core-web-api-ef-core-code-first/ 使用 .NET 6.0 设置我的后端(在文章中他们使用的是 5)。
我在 Postman 上收到此错误(尝试测试 API):
System.InvalidOperationException: Unable to resolve service for type 'codeFirstExample.Models.Repository.IDataRepository`1[codeFirstExample.Models.Employee]' while attempting to activate 'codeFirstExample.Controllers.EmployeeController'
这是我的代码:
型号(Employee.cs):
namespace codeFirstExample.Models
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long EmployeeId { get; set; }
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
}
DbContext (EmployeeContext.cs):
namespace codeFirstExample.Models
{
public class EmployeeContext : DbContext
{
private readonly IConfiguration Configuration;
public EmployeeContext(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<EmployeeContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:EmployeeDB"]));
services.AddScoped<IDataRepository<Employee>, EmployeeManager>();
services.AddControllers();
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// connect to sql server with connection string from app settings
options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().HasData(new Employee
{
EmployeeId = 1,
FirstName = "Uncle",
LastName = "Bob",
Email = "uncle.bob@gmail.com",
PhoneNumber = "999-888-7777"
}, new Employee
{
EmployeeId = 2,
FirstName = "Jan",
LastName = "Kirsten",
Email = "jan.kirsten@gmail.com",
PhoneNumber = "111-222-3333"
});
}
public DbSet<Employee> Employees => Set<Employee>();
}
}
存储库(IDataRepository.cs):
namespace codeFirstExample.Models.Repository
{
public interface IDataRepository<TEntity>
{
IEnumerable<TEntity> GetAll();
TEntity Get(long id);
void Add(TEntity entity);
void Update(TEntity dbEntity, TEntity entity);
void Delete(TEntity entity);
}
}
控制器(EmployeeController.cs):
namespace codeFirstExample.Controllers
{
[Route("api/employee")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IDataRepository<Employee> _dataRepository;
public EmployeeController(IDataRepository<Employee> dataRepository, EmployeeContext context)
{
_dataRepository = dataRepository;
}
// GET: api/Employee
[HttpGet]
public IActionResult Get()
{
IEnumerable<Employee> employees = _dataRepository.GetAll();
return Ok(employees);
}
// GET: api/Employee/5
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(int id)
{
Employee employee = _dataRepository.Get(id);
if (employee == null)
{
return NotFound("The Employee record couldn't be found.");
}
return Ok(employee);
}
// POST: api/Employee
[HttpPost]
public IActionResult Post([FromBody] Employee employee)
{
if (employee == null)
{
return BadRequest("Employee is null.");
}
_dataRepository.Add(employee);
return CreatedAtRoute(
"Get",
new { Id = employee.EmployeeId },
employee);
}
// PUT: api/Employee/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Employee employee)
{
if (employee == null)
{
return BadRequest("Employee is null.");
}
Employee employeeToUpdate = _dataRepository.Get(id);
if (employeeToUpdate == null)
{
return NotFound("The Employee record couldn't be found.");
}
_dataRepository.Update(employeeToUpdate, employee);
return NoContent();
}
// DELETE: api/Employee/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
Employee employee = _dataRepository.Get(id);
if (employee == null)
{
return NotFound("The Employee record couldn't be found.");
}
_dataRepository.Delete(employee);
return NoContent();
}
}
}
我不确定出了什么问题,有人可以帮我解决这个问题吗?
在 Startup.cs 的 ConfigureServices 方法中添加您的服务,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<EmployeeContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:EmployeeDB"]));
services.AddScoped<IDataRepository<Employee>, EmployeeManager>();
services.AddControllers();
}
我正在关注这篇文章:https://code-maze.com/net-core-web-api-ef-core-code-first/ 使用 .NET 6.0 设置我的后端(在文章中他们使用的是 5)。
我在 Postman 上收到此错误(尝试测试 API):
System.InvalidOperationException: Unable to resolve service for type 'codeFirstExample.Models.Repository.IDataRepository`1[codeFirstExample.Models.Employee]' while attempting to activate 'codeFirstExample.Controllers.EmployeeController'
这是我的代码:
型号(Employee.cs):
namespace codeFirstExample.Models
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long EmployeeId { get; set; }
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
}
DbContext (EmployeeContext.cs):
namespace codeFirstExample.Models
{
public class EmployeeContext : DbContext
{
private readonly IConfiguration Configuration;
public EmployeeContext(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<EmployeeContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:EmployeeDB"]));
services.AddScoped<IDataRepository<Employee>, EmployeeManager>();
services.AddControllers();
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// connect to sql server with connection string from app settings
options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().HasData(new Employee
{
EmployeeId = 1,
FirstName = "Uncle",
LastName = "Bob",
Email = "uncle.bob@gmail.com",
PhoneNumber = "999-888-7777"
}, new Employee
{
EmployeeId = 2,
FirstName = "Jan",
LastName = "Kirsten",
Email = "jan.kirsten@gmail.com",
PhoneNumber = "111-222-3333"
});
}
public DbSet<Employee> Employees => Set<Employee>();
}
}
存储库(IDataRepository.cs):
namespace codeFirstExample.Models.Repository
{
public interface IDataRepository<TEntity>
{
IEnumerable<TEntity> GetAll();
TEntity Get(long id);
void Add(TEntity entity);
void Update(TEntity dbEntity, TEntity entity);
void Delete(TEntity entity);
}
}
控制器(EmployeeController.cs):
namespace codeFirstExample.Controllers
{
[Route("api/employee")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IDataRepository<Employee> _dataRepository;
public EmployeeController(IDataRepository<Employee> dataRepository, EmployeeContext context)
{
_dataRepository = dataRepository;
}
// GET: api/Employee
[HttpGet]
public IActionResult Get()
{
IEnumerable<Employee> employees = _dataRepository.GetAll();
return Ok(employees);
}
// GET: api/Employee/5
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(int id)
{
Employee employee = _dataRepository.Get(id);
if (employee == null)
{
return NotFound("The Employee record couldn't be found.");
}
return Ok(employee);
}
// POST: api/Employee
[HttpPost]
public IActionResult Post([FromBody] Employee employee)
{
if (employee == null)
{
return BadRequest("Employee is null.");
}
_dataRepository.Add(employee);
return CreatedAtRoute(
"Get",
new { Id = employee.EmployeeId },
employee);
}
// PUT: api/Employee/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Employee employee)
{
if (employee == null)
{
return BadRequest("Employee is null.");
}
Employee employeeToUpdate = _dataRepository.Get(id);
if (employeeToUpdate == null)
{
return NotFound("The Employee record couldn't be found.");
}
_dataRepository.Update(employeeToUpdate, employee);
return NoContent();
}
// DELETE: api/Employee/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
Employee employee = _dataRepository.Get(id);
if (employee == null)
{
return NotFound("The Employee record couldn't be found.");
}
_dataRepository.Delete(employee);
return NoContent();
}
}
}
我不确定出了什么问题,有人可以帮我解决这个问题吗?
在 Startup.cs 的 ConfigureServices 方法中添加您的服务,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<EmployeeContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:EmployeeDB"]));
services.AddScoped<IDataRepository<Employee>, EmployeeManager>();
services.AddControllers();
}