在EF Core 2.2的控制器之外访问DBContext

时间:2019-03-06 11:23:01

标签: c# database asp.net-core dbcontext ef-core-2.2

我想在控制器外部的另一个类(称为FileWatcher)中访问数据库/ dbContext。该Web应用程序还使用Hangfire不断侦听新创建文件的目录,它需要解析这些文件并将信息添加到数据库中。

所以我的startup.cs看起来像:

    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?}");
        });
    }

我的FileWatcher类:

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 
    }
}

我的dbContext文件:

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

    public DbSet<Car> Cars { get; set; }
    public DbSet<Van> Vans{ get; set; }
}
抱歉,如果信息不足,我将在需要/要求时提供更多信息。 如果有人可以提供解决方案,并且我的代码可以针对我的需要进行改进,我将不胜感激。

1 个答案:

答案 0 :(得分:3)

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());