EF Core 6 简化的数据库上下文注册
Intro
EF Core 6 将简化现在的服务注册,DbContext
的服务注册将会更简单一些
Sample
直接来看示例代码吧:
现在我们注册 EF Core 的 DbContext
通常是这样的:
const string connectionString = "DataSource=test";
var services = new ServiceCollection();
services.AddDbContext<TestDbContext>(options => options.UseSqlite(connectionString));
在 EF Core 6 中将会得以简化成下面的形式:
const string connectionString = "DataSource=test";
var services = new ServiceCollection();
services.AddSqlite<TestDbContext>(connectionString);
这两种方式是完全等价的
完整示例:
const string connectionString = "DataSource=test";
var services = new ServiceCollection();
services.AddSqlite<TestDbContext>(connectionString);
using var serviceProvider = services.BuildServiceProvider();
using var scope = serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TestDbContext>();
dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();
dbContext.Users.Add(new User
{
Name = "Alice",
CreatedAt = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
var users = await dbContext.Users.AsNoTracking().ToArrayAsync();
users.Dump();
输出如下,可以看出来工作正常
示例代码完整代码可以从 Github 获取:https://github.com/WeihanLi/SamplesInPractice/blob/master/EF6Samples/Program.cs
Implement
其实现方式其实就是封装了一个扩展方法,扩展方法实现如下:
public static IServiceCollection AddSqlite<TContext>(this IServiceCollection serviceCollection, string connectionString, Action<SqliteDbContextOptionsBuilder>? sqliteOptionsAction = null, Action<DbContextOptionsBuilder>? optionsAction = null)
where TContext : DbContext
{
Check.NotNull(serviceCollection, nameof(serviceCollection));
Check.NotEmpty(connectionString, nameof(connectionString));
return serviceCollection.AddDbContext<TContext>((serviceProvider, options) =>
{
optionsAction?.Invoke(options);
options.UseSqlite(connectionString, sqliteOptionsAction);
});
}
更多细节可以参考 Github 上的 issue 和 pr
https://github.com/dotnet/efcore/issues/25192
https://github.com/dotnet/efcore/pull/25220
References
https://github.com/dotnet/efcore/issues/25192
https://github.com/dotnet/efcore/pull/25220
https://github.com/WeihanLi/SamplesInPractice/blob/master/EF6Samples/Program.cs