public static IServiceCollection AddDbContext<TContextService, TContextImplementation>(
[NotNull] this IServiceCollection serviceCollection,
[CanBeNull] Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContextImplementation : DbContext, TContextService
{
Check.NotNull(serviceCollection, nameof(serviceCollection));
if (contextLifetime == ServiceLifetime.Singleton)
{
optionsLifetime = ServiceLifetime.Singleton;
}
if (optionsAction != null)
{
CheckContextConstructors<TContextImplementation>();
}
AddCoreServices<TContextImplementation>(serviceCollection, optionsAction, optionsLifetime);
serviceCollection.TryAdd(new ServiceDescriptor(typeof(TContextService), typeof(TContextImplementation), contextLifetime));
return serviceCollection;
}
private static void AddCoreServices<TContextImplementation>(
IServiceCollection serviceCollection,
Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
ServiceLifetime optionsLifetime)
where TContextImplementation : DbContext
{
serviceCollection.TryAdd(
new ServiceDescriptor(
typeof(DbContextOptions<TContextImplementation>),
p => DbContextOptionsFactory<TContextImplementation>(p, optionsAction),
optionsLifetime));
serviceCollection.Add(
new ServiceDescriptor(
typeof(DbContextOptions),
p => p.GetRequiredService<DbContextOptions<TContextImplementation>>(),
optionsLifetime));
}
private static DbContextOptions<TContext> DbContextOptionsFactory<TContext>(
[NotNull] IServiceProvider applicationServiceProvider,
[CanBeNull] Action<IServiceProvider, DbContextOptionsBuilder> optionsAction)
where TContext : DbContext
{
var builder = new DbContextOptionsBuilder<TContext>(
new DbContextOptions<TContext>(new Dictionary<Type, IDbContextOptionsExtension>()));
builder.UseApplicationServiceProvider(applicationServiceProvider);
optionsAction?.Invoke(applicationServiceProvider, builder);
return builder.Options;
}
private static void CheckContextConstructors<TContext>()
where TContext : DbContext
{
var declaredConstructors = typeof(TContext).GetTypeInfo().DeclaredConstructors.ToList();
if (declaredConstructors.Count == 1
&& declaredConstructors[0].GetParameters().Length == 0)
{
throw new ArgumentException(CoreStrings.DbContextMissingConstructor(typeof(TContext).ShortDisplayName()));
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章