简体   繁体   中英

Singleton service and EF Core dbContext

The application uses ASP.NET Core 3. At the first call, a project class service is created.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    string connection = Configuration.GetConnectionString("ConnectionDB");
    services.AddDbContext<DataBaseContext>(options => options.UseSqlServer(connection), ServiceLifetime.Transient, ServiceLifetime.Singleton);

    services.AddSingleton<Project>();
}

Project.cs

public class Project
{
    private readonly DataBaseContext _dbContext;

    public Project(DataBaseContext dbContext)
    {
        _dbContext = dbContext;
        Init();
    }   

    public async void Init()
    {
        await SomeMethod('text');
    }

    public async Task SomeMethod(string message)
    {
        _dbContext.Items.Add(message);
        await _dbContext.SaveChangesAsync();
    }
}

This is not entirely correct and I want to create a service when the application starts.

public void ConfigureServices(IServiceCollection services)
{
    // AddDbContext

    Project project = new Project(dbContext); // How to get dbcontext?
    services.AddSingleton(typeof(Project), project);
}

How to pass dbcontext in this case?

UPDATE Now in the Stratup class, I call the init () method of the project service. Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
    Project project = serviceProvider.GetService<Project>();
    project.Init();

    // some code
}

Dunno why would you not use the automatic Dependecy Injection at your first code

Singleton are created upon app start. And as long as the init method is called inside the constructor it will run. So this code will work on your case already

public void ConfigureServices(IServiceCollection services)
{
    string connection = Configuration.GetConnectionString("ConnectionDB");
    services.AddDbContext<DataBaseContext>(options => options.UseSqlServer(connection), ServiceLifetime.Transient, ServiceLifetime.Singleton);

    services.AddSingleton<Project>();
}

But anyway if you insist on instantiating the Project class then you can use this. Get the DBContext using ServiceProvider.

public void ConfigureServices(IServiceCollection services)
{
    // AddDbContext
    var sp = services.BuildServiceProvider();
    var dbContext = sp.GetRequiredService<DbContext>();
    Project project = new Project(dbContext); 
    services.AddSingleton(typeof(Project), project);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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