How to update DB in singleton instance?

asp.net-core c# entity-framework-core singleton

Question

My app uses a singleton pattern for a handler class instance. It is responsible for handling some events:

public class MyHandler
{
    public void HandlerEvent(object sender, EventArgs e)
    {
        //want to update DB here
    }
}

It is possibly MyHandler will need to start interaction with DB. So can I do it? There is my vision:

  1. Just tough attach DbContext as singleton at MyHandler. Obviously it's a bad idea.
  2. Use ASP.Net Core DI features and send DbContext to MyHandler, but as an instance "one per request". I think in my case (MyHandler is singleton) this is similar to 1
  3. Do it through using operator, i.e. as atomic transaction, for e.g. using(var context = new XDbContext()) {...} As for me it's a good approach, but DbContext of Entity Framework Core implementation needs DbContextOptions as argument of its constructor. If I declare parameterless constructor for XDbContext then it throws an exception.

Any ideas?

1
1
12/25/2016 3:48:36 AM

Popular Answer

I've seen an ef core tutorial (https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext) and as I understood, DbContextOptions - is just an object with configuration parameters inside it. If I had same problem, I would use the third way (with using), but would create a helper for injecting parameters or using a factory for this. I found an example of factory in the tutorial

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace MyProject
{
   public class BloggingContextFactory : IDbContextFactory<BloggingContext>
   {
       public BloggingContext Create()
       {
          var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
          optionsBuilder.UseSqlite("Filename=./blog.db");

          return new BloggingContext(optionsBuilder.Options);
       }
   }
}

Example of using:

public class MyHandler
{
   public void HandlerEvent(object sender, EventArgs e)
   {
       // Or make 'Create' method static
       using(var context = new BloggingContextFactory().Create())
       {
                 . . . 
       }
   }
}
1
12/25/2016 7:57:31 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow