yigames
yigames

Reputation: 185

Access DBContext outside of controller for EF Core 2.2

I want to access the database / dbContext in another class (called FileWatcher) outside of the controllers. This web application also uses Hangfire to constantly listen to a directory for newly created files, it needs to parse the files and add the information into a database.

so my startup.cs looks like:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<JobsContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddHangfire(config =>
            config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHangfireDashboard("/hangfire");
        app.UseHangfireServer();
        FileWatcher = new FileWatcher();
        BackgroundJob.Enqueue(() => FileWatcher.Watch());

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

my FileWatcher class:

public class FileWatcher 
{
    private string inbound_path = "Inbound";

    public void Watch()
    {
        var watcher = new FileSystemWatcher();
        watcher.Path = inbound_path;
        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
        watcher.Filter = "*.*";
        watcher.Created += new FileSystemEventHandler(OnCreated);            
        watcher.EnableRaisingEvents = true;            
    }

    private void OnCreated(object source, FileSystemEventArgs e)
    {
        //SOME FILE PARSING METHOD WILL BE INVOKED HERE WHICH RETURNS A MODEL
        //ACCESS DB HERE AND 
    }
}

my dbContext file:

public class dbContext : DbContext
{
    public dbContext(DbContextOptions<dbContext> options) : base(options)
    {
    }

    public DbSet<Car> Cars { get; set; }
    public DbSet<Van> Vans{ get; set; }
}

apologies if insufficient information, i will provide further information if required/asked. would highly appreciate if someone can provide a solution and if my code can be improved for what i need it for.

Upvotes: 1

Views: 4688

Answers (1)

DavidG
DavidG

Reputation: 118937

You should not be newing up the FileWatcher class, use the DI framework and the context will come with it. First change the FileWatcher class to inject the context:

public class FileWatcher 
{
    private readonly dbContext _context;

    public FileWatcher(dbContext context)
    {
        _context = context;
    }
}

Now add FileWatcher to the DI container in the ConfigureServices method:

//Generally I would prefer to use an interface here, e.g. IFileWatcher
services.AddScoped<FileWatcher>();

Finally, in the Configure method, make use of the Hangfire overload to use the DI system:

//Remove this line completely, it is not needed.
//FileWatcher = new FileWatcher();

//Use the generic overload and the FileWatcher object will be injected for you
BackgroundJob.Enqueue<FileWatcher>(fw => fw.Watch());

Upvotes: 7

Related Questions