【发布时间】:2015-03-30 02:35:41
【问题描述】:
我正在尝试使用 ASP.Net vNext、MVC、EF7 和存储库模式(这里不是问题,我不认为)...
我遇到的问题是,当对数据库发出多个请求时,我收到以下错误:“已经有一个打开的 DataReader 与此命令关联,必须先关闭。”
这里有一些代码:
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
Configuration = new Configuration().AddJsonFile("config.json").AddEnvironmentVariables();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Register Entity Framework
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<MyDbContext>();
services.AddSingleton<ILocationRepo, LocationRepo>();
services.AddSingleton<IStateRepo, StateRepo>();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
var testData = ActivatorUtilities.CreateInstance<TestData>(app.ApplicationServices);
testData.InitializeData();
}
}
控制器:
[Route("api/[controller]")]
public class LocationsController : Controller
{
private readonly ILocationRepo _repo;
public LocationsController(ILocationRepo repo)
{
_repo = repo;
}
// GET: api/locations
[HttpGet]
public List<Location> Get()
{
return _repo.All.ToList();
}
// GET api/locations/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var ret = _repo.GetById(id);
if (ret == null)
return new HttpNotFoundResult();
return new ObjectResult(ret);
}
// POST api/locations
[HttpPost]
public IActionResult Post([FromBody]Locationvalue)
{
var ret = _repo.AddOrUpdate(value);
if (ret == null)
return new BadRequestResult();
return new ObjectResult(ret);
}
// PUT api/locations/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Location value)
{
var ret = _repo.AddOrUpdate(value);
if (id == 0 || ret == null)
return new BadRequestResult();
return new ObjectResult(ret);
}
// DELETE api/locations/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var existing = _repo.GetById(id);
if (existing == null)
return new HttpNotFoundResult();
bool ret = _repo.TryDelete(id);
return new ObjectResult(ret);
}
}
States 存储库:
public class StateRepo : IStateRepo
{
private readonly MyDbContext context;
public StateRepo(MyDbContext diContext)
{
context = diContext;
}
public IEnumerable<State> All
{
get
{
return context.States;
}
}
public State GetById(int id)
{
return context.States.FirstOrDefault(x => x.Id == id);
}
}
我对 Locations 有几乎相同的 repo 设置(当然还有更多方法)......当我同时对我的位置和状态控制器进行 AJAX 调用时,问题就出现了。我希望上下文的 DI 能够处理此类冲突,但它似乎没有这样做。是否有另一种方法可以将其配置为正常工作,而不必回到在整个存储库中创建上下文实例的旧方法?是不是我有什么配置不正确?
【问题讨论】:
标签: dependency-injection repository-pattern asp.net-core asp.net-core-mvc