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

问题描述 投票:0回答:1

我想访问控制器之外的另一个类(称为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; }
}

如果信息不足,我会道歉,如果需要/要求,我会提供进一步的信息。如果有人能提供解决方案,并且我的代码可以根据我的需要进行改进,我将非常感激。

c# database asp.net-core dbcontext ef-core-2.2
1个回答
4
投票

你不应该是newing 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());
© www.soinside.com 2019 - 2024. All rights reserved.