JDF*_*JDF 0 dependency-injection repository-pattern asp.net-core-mvc asp.net-core
我试图使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
控制器:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
国家储存库:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我对Locations有很多相同的repo设置(当然还有一些方法)......当我同时向我的位置和状态控制器进行AJAX调用时,问题出现了.我希望上下文的DI能够处理这种冲突,但它似乎并没有这样做.还有另一种方法可以将其配置为正常工作而无需回到在我的回购中创建我的上下文实例的旧方法吗?我有什么配置错误吗?
我并不声称自己是DI专家,但尝试使用AddScoped而不是AddSingleton注册您的存储库.我认为你为每个请求获得了相同的存储库实例,它可能具有相同的DbContext实例,并且DbContext不是线程安全的.
另外,请确保您的connectionstring中有MultipleActiveResultSets = true.我认为这也可能导致你看到的错误.
| 归档时间: |
|
| 查看次数: |
1238 次 |
| 最近记录: |