我有一个控制器,其开头如下:
[Route("api/[controller]")]
public class PersonsController : BaseController
到目前为止, BaseController
看起来像这样:
public class BaseController : Controller
{
public BaseController(CompanyDbContext dbContext)
{
Db = dbContext;
}
protected CompanyDbContext Db;
}
PersonsController
有一些获取,一个帖子,一个放置和一个删除。除了Delete
操作之外的所有操作都可以正常工作,解决注入的CompanyDbContext
没有问题。
Delete
操作如下所示:
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var pers = await Db.Persons.SingleOrDefaultAsync(p => p.PersonId == id);
if (pers == null)
{
return NotFound();
}
Db.Remove(pers);
await Db.SaveChangesAsync();
return Ok();
}
然而,当我执行删除请求时:
public async Task DeletePersonAsync(int id)
{
var resp = await _client.DeleteAsync($"api/Persons/{id}");
resp.EnsureSuccessStatusCode();
}
其中_client
是HttpClient
,我收到以下错误:
InvalidOperationException:无法解析类型的服务 &#39; AcmeSoft.Api.Data.CompanyDbContext&#39;在尝试激活时 &#39; AcmeSoft.Api.Controllers.PersonsController&#39;
我使用的是默认的内置DI,它带有一个新的MVC Core 2.0项目。我在类Startup
中注册了上下文服务,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CompanyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
然而,除Delete
之外,所有操作的服务都能正常解析。这可能有什么问题?我哪里出错?
对于喜欢长问题的人,整个PersonsController
如下:
[Route("api/[controller]")]
public class PersonsController : BaseController
{
public PersonsController(CompanyDbContext dbContext) : base(dbContext)
{
}
[HttpGet]
public IActionResult Get()
{
var persons = Db.Persons.ToList();
return Ok(persons);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var pers = await Db.Persons.SingleOrDefaultAsync(p => p.PersonId == id);
if (pers == null)
{
return Ok(null);
}
return Ok(pers);
}
[HttpGet("GetByIdNumber/{idNumber}")]
public async Task<IActionResult> GetByIdNumber(string idNumber)
{
var pers = await Db.Persons.SingleOrDefaultAsync(e => e.IdNumber == idNumber);
if (pers == null)
{
return Ok(null);
}
return Ok(pers);
}
[HttpGet("PersonEmployees")]
public async Task<IActionResult> PersonEmployees()
{
var emps = await Db.PersonEmployees.ToListAsync();
return Ok(emps);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] Person person)
{
Db.Add(person);
await Db.SaveChangesAsync();
return Ok(person);
}
[HttpPut]
public async Task<IActionResult> Put([FromBody] Person person)
{
Db.Update(person);
await Db.SaveChangesAsync();
return Ok(person);
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var pers = await Db.Persons.SingleOrDefaultAsync(p => p.PersonId == id);
if (pers == null)
{
return NotFound();
}
Db.Remove(pers);
await Db.SaveChangesAsync();
return Ok();
}
}
除删除工作以外的所有操作。
ADDED:开发人员错误页面上显示的堆栈跟踪是:
System.InvalidOperationException: Unable to resolve service for type 'AcmeSoft.Api.Data.CompanyDbContext' while attempting to activate 'AcmeSoft.Api.Controllers.PersonsController'.
at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()