我有一个WebApi控制器,它在OWIN Startup类中有AutoFac注入的服务
builder.Register(c => new MyEntities()).InstancePerRequest();
我也试过了
builder.Register(c => new MyEntities()).InstancePerLifetimeScope();
在控制器操作中,我调用服务方法来创建新记录,通过HttpClient将创建的id传递给外部api以获取更多数据,然后使用一些返回数据更新新记录.
[HttpPost, Route("")] public async TaskMyControllerAction(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 TaskCreateNewThing(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(); } }
但是我InvalidOperationException
在UpdateNewThing中得到了一个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这样的东西; 除非有人能发现我错过的简单内容,否则我会继续这个设计.