我有一个WebApi控制器,它在OWIN Startup类中有AutoFac注入的服务
builder.Register(c => new MyEntities()).InstancePerRequest();
我也试过
builder.Register(c => new MyEntities()).InstancePerLifetimeScope();
在一个控制器动作中,我调用一个服务方法来创建一个新记录,通过HttpClient将创建的id传递给外部api以获取更多数据,然后用一些返回数据更新新记录。
[HttpPost, Route("")]
public async Task<IHttpActionResult> MyControllerAction(MyModel model)
{
var id = await _MyService.CreateNewThing(model.SomeId);
var externalData = await CallExternalApiThroughHttpClient(id);
await _MyService.UpdateNewThing(id, externalData);
return Ok();
}
服务代码
public class MyService : IMyService
{
private MyEntities _context;
public MyService(MyEntities context)
{
_context = context;
}
public async Task<int> CreateNewThing(int someId)
{
var thing = new Thing
{
SomeId = someId
};
_context.Things.Add(thing);
await _context.SaveChangesAsync();
return thing.Id;
}
public async Task UpdateNewThing(int id, string externalDataField)
{
var thing = await _context.Things.SingleOrDefaultAsync(o => o.Id == id);
if (thing == null)
{
throw new ServiceNotFoundException("Thing " + transactionId + " not found");
}
thing.ExternalDataField= externalDataField;
await _context.SaveChangesAsync();
}
}
但我在UpdateNewThing InvalidOperationException
var thing = await _context.Things.SingleOrDefaultAsync(o => o.Id == id);
System.InvalidOperationException: The connection was not closed. The connection's current state is connecting.
似乎我不得不放弃注入上下文,异步/等待或使用像contextfactory这样的东西;除非有人能发现我错过的简单内容,否则我会继续这个设计。