Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to use a service worker with a EF using dbContext:
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
       {
       }

       DbSet<SimulationParcelData> SimulationParcelData { get; set; }

       protected override void OnModelCreating(ModelBuilder modelBuilder)
       {
           modelBuilder.Entity<SimulationParcelData>().ToTable("SimulationParcels");
       }

But i can not find the way to use inyection in the worker.cs file

This is the code in programs.cs

.ConfigureServices((hostContext, services) =>
              {
                  //var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
                  //optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=xxx;Trusted_Connection=True;");//,
                  //services.AddScoped<ApplicationDbContext>(s => new ApplicationDbContext(optionsBuilder.Options));

                  services.AddDbContext<ApplicationDbContext>(options =>
                  {
                      options.UseSqlServer(
                          hostContext.Configuration["ConnectionStrings:Connection"],
                          serverDbContextOptionsBuilder =>
                          {
                              var minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
                              serverDbContextOptionsBuilder.CommandTimeout(minutes);
                              serverDbContextOptionsBuilder.EnableRetryOnFailure();
                          });
                  });
                  services.AddScoped<ApplicationDbContext>();
                  services.AddHostedService<Worker>();

              });


I am sure i am doing something wrong, but i do not know.
Any helps?

What I have tried:

I have tried serveral way to use EI in a Service work, but everything wrong
I am using C#
Posted
Updated 14-Jun-22 3:36am

Try the documentation:
To use scoped services within a BackgroundService, create a scope. No scope is created for a hosted service by default.
It even gives you a clear example of how to do that.
 
Share this answer
 
Thanks at lot Richard, I also found this:
Creating Worker Service + Entity Framework Core in .NET[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900