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:
- Just tough attach
DbContext
as singleton atMyHandler
. Obviously it's a bad idea. - Use ASP.Net Core DI features and send
DbContext
toMyHandler
, but as an instance "one per request". I think in my case (MyHandler
is singleton) this is similar to 1 - 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 needsDbContextOptions
as argument of its constructor. If I declare parameterless constructor for XDbContext then it throws an exception.
Any ideas?
DbContext
property in yourMyHandler
class and in it's get renew your instance ofXDbContext
you don't need to worry about previous instances since they'll be collected via GC.HandlerEvent
processes messages which arrives from azure service bus, i.e. it does not depend on http-requests