Singleton service and EF Core dbContext

asp.net-core c# entity-framework entity-framework-core

Question

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
}
1
0
10/30/2019 5:16:54 AM

Accepted Answer

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);
}
1
10/30/2019 4:48:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow