Menu

Asp.net core 2.0 and Entity framework Core – registering DbContext with ServiceLifetime.Transient

In your Startup.cs file you need to register the DbContext in order to use it throughout the application if you don’t register it as ServiceLifetime.Transient you will encounter threading issues as by default its ServiceLifetime.Scoped.

ServiceLifetime.Singleton: A single shared instance throughout your application’s lifetime. Only created once.

ServiceLifetime.Scoped: Shared within a single request (or Service Scope).

ServiceLifetime.Transient: Created on every request for the service.

this is how to register it as ServiceLifetime.Transient

public void ConfigureServices(IServiceCollection services)
{
  .....
  services.AddDbContext<MyDatabaseContext>(options =>
                options.UseSqlServer(configuration.GetConnectionString(AppSettingConstants.ConnectionString),
                migration => migration.MigrationsHistoryTable(MyDatabaseConstants.MigrationsHistoryTableName, MyDatabaseConstants.DatabaseSchemaName)),
                ServiceLifetime.Transient);
  .....
}

Hope this helps.

Leave a comment