In-memory database doesn’t save data

Your code has multiple serious problems, let’s go through them.

  1. services.AddDbContext adds a Scoped service, meaning that instances will be created and disposed on each request. services.AddSingleton adds a Singleton service, so only a single instance will ever be created. You cannot add a scoped service to a singleton one, because the reference the singleton service uses will be disposed and you will end up with a disposed context.

  2. This code:

     return provider.GetService<IUnitOfWork>();
    

represents the service locator anti-pattern. As you can guess, an anti-pattern is something you want to avoid. I also don’t know why you would want a service to build the entire DI container nor why you would want a service to have the responsibility of getting the dependencies it needs itself.

  1. This part here is where your question actually comes from:

     Database.SaveAsync();
    

You are calling an asynchronous function and not awaiting for it to finish. The task may finish or not, it may throw an error or not, you will never know what happened.

The best thing is that all of these could be avoided if people stopped attempting to create a Unit of Work + Repository pattern over yet another Unit of Work and Repository. Entity Framework Core already implements these:

DbContext => Unit of Work
DbSet => Repository (generic)

Why do you want yet another abstraction? Will you really ever throw away EF Core from the project to justify the maintenance cost of your code?

The entire question code could have just been this:

[Route("api/[controller]")]
public class ItemsController : Controller
{
    private readonly YourContext _context;

    public ItemsController(YourContext context)
    {
       _context = context;
    }

    [HttpPost]
    public async Task<IActionResult> Add([FromBody]Item item)
    {
        context.Items.Add(item);
        await context.SaveChangesAsync();

        return Ok(item.Id);
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        var item = await context.Items.FindAsync(id);
        context.Items.Remove(item);
        await context.SaveChangesAsync();

        return Ok();
    }

    [HttpPut]
    public async Task<IActionResult> Put([FromBody]Item item)
    {
        context.Items.Update(item);
        await context.SaveChangesAsync();

        return Ok();
    }
}

Leave a Comment