EF Core 2.2的控制器外部访问DBContext



我想在控制器外部访问另一个类(称为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?}");
        });
    }

我的文件观察者类:

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

道歉,如果信息不足,我将在需要/询问的情况下提供更多信息。如果有人可以提供解决方案,并且我的代码可以改进我需要的内容。

您不应将 new上升到FileWatcher类,使用DI框架,并且上下文将随附。首先更改FileWatcher类以注入上下文:

public class FileWatcher 
{
    private readonly dbContext _context;
    public FileWatcher(dbContext context)
    {
        _context = context;
    }
}

现在,将FileWatcher添加到ConfigureServices方法中的DI容器:

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

最后,在Configure方法中,使用hangfire超载使用DI系统:

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

最新更新