ASP.Net vNext DbContext Dependency Injection multiple request issues.

拟墨画扇 提交于 2020-01-17 05:54:38

问题


I am attempting to use ASP.Net vNext, MVC, EF7, and the repository pattern (not the issue here, I don't think)...

The issue I'm having is that when multiple requests are made against the database, I'm getting the following error: "There is already an open DataReader associated with this Command which must be closed first."

Here's some code:

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();
    }
}

The controller:

[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);
    }
}

The States repository:

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);
    }
}

I have pretty much the same repo setup for Locations (with a few more methods, of course)... the problem comes in when I'm making simultaneous AJAX calls to my locations and states controllers. I would expect the DI for the context to handle such collisions, but it doesn't appear to be doing so. Is there another way to configure this to work correctly without having to go back to the old way of creating an instance of my context throughout my repos? Do I have anything configured incorrectly?


回答1:


I don't claim to be a DI expert, but try registering your repositories with AddScoped instead of AddSingleton. I think you are getting the same instance of the repository for each request which probably has the same instance of your DbContext and DbContext is not thread safe.

Also, make sure you have MultipleActiveResultSets=true in your connectionstring. I think that can also cause the error you are seeing.



来源:https://stackoverflow.com/questions/29332494/asp-net-vnext-dbcontext-dependency-injection-multiple-request-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!