Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

What is the proper way to get the workDbContext for a worker? #9196


User avatar
0
marble68 created

I need a worker to do multitenant work on the database - so in the DoWork function I would like to use the DB context.

The worker class lives the Core project.

The reason is I need to to linq queries involving datetimes and these don't work through reposities.

my linq looks like this:

                   allShifts = allShifts
                                            .Where(s =>
                                               TimeSpan.Compare(s.Deadline.ToUniversalTime().AddHours(s.NotifyHoursBeforeDeadline * -1).TimeOfDay, _notificationSweep.TimeOfDay) < 0 // The deadline is after now
                                                &&
                                                _notificationSweep.TimeOfDay.TotalMinutes - s.Deadline.ToUniversalTime().AddHours(s.NotifyHoursBeforeDeadline * -1).TimeOfDay.TotalMinutes < NotificationWindowInMinutes + 5 // it's within 30 minutes, adding 5 minutes to account for sending time
                                            )
                                            .ToList();

If I can get to the workDbContext, I should be able to use some of the dbFunctions specified here: https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.sqlserverdbfunctionsextensions?view=efcore-3.1

What this is trying to do:

I have a datetime object I only need the timeofday - so I have now which is the notificationsweep variable.

I need to get time of day values that are within 30 minutes of the job running.

My hope is geting the DB context would allow better querying flexibilty.


4 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You can inject IDbContextProvider and use it to get the DbContext.

  • User Avatar
    0
    marble68 created

    For a domain service? It doesn't have a reference to my DbContext which is in Framework core.

  • User Avatar
    0
    maliming created
    Support Team

    You may consider moving the worker to the EF layer. Or abstracting it as an interface in the Domain and implementing it in the EF layer.

  • User Avatar
    0
    marble68 created

    Thank you - this worked.

    I had a few issues because I forgot to inherit from ISingletonDependency - but as soon as I did that, the job started correctly.