简体   繁体   English

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

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

so my startup.cs looks like: 所以我的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?}");
        });
    }

my FileWatcher class: 我的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 
    }
}

my dbContext file: 我的dbContext文件:

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. 如果有人可以提供解决方案,并且我的代码可以针对我的需要进行改进,我将不胜感激。

You should not be new ing up the FileWatcher class, use the DI framework and the context will come with it. 您不应该new FileWatcher类,而是使用DI框架,上下文将随之而来。 First change the FileWatcher class to inject the context: 首先更改FileWatcher类以注入上下文:

public class FileWatcher 
{
    private readonly dbContext _context;

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

Now add FileWatcher to the DI container in the ConfigureServices method: 现在,在ConfigureServices方法中将FileWatcher添加到DI容器中:

//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: 最后,在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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM