I have this code in my Program.cs
in.NET 6.
var idConnectionString = builder.Configuration.GetConnectionString("IdentityConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(idConnectionString));
var abcConnectionString = builder.Configuration.GetConnectionString("abcConnection");
builder.Services.RegisterSqlServer<AbcDbContext>(abcConnectionString);
var xyzConnectionString = builder.Configuration.GetConnectionString("xyzConnection");
builder.Services.AddDbContext<XzyDbContext>(x => x.UseSqlServer(xyzConnectionString));
How do I move these code into my Service extension class?
public static class ServiceExtensions
{
public static IServiceCollection AddDbContextServices(this IServiceCollection services)
{
??
return services;
}
}
Create a static class DbContext as following:
public static class DbContext
{
public static IServiceCollection AddCustomizedDbContext(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetSection("ConnectionStrings:Connectionstring").Value;
var migrationsAssembly = "NameSpace";
services.AddDbContext<DBContext>(options =>
options.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly))
);
return services;
}
}
Then Register it in startup:
services.AddCustomizedDbContext(configuration);
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.