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 }