0
0
Files
Extensions.Configuration.En…/RAIC.Extensions.Configuration.EntityFrameworkCore/Extensions/ConfigurationBuilderExtensions.cs

35 lines
1.8 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace RAIC.Extensions.Configuration.EntityFrameworkCore.Extensions;
public static class ConfigurationBuilderExtensions
{
public delegate DbContextOptionsBuilder<T> DbContextOptionsTransformer<T>(DbContextOptionsBuilder<T> transform) where T : DbContext;
/// <summary>
/// Adds a <see cref="DbSet{}"/> off <typeparamref name="TDbContext"/> as a configuration provider to the <see cref="IConfigurationBuilder"/>.
/// </summary>
/// <typeparam name="TDbContext">Type of the <see cref="DbContext"/> which implements <see cref="ISettingsDbContext{,}"/></typeparam>
/// <typeparam name="TSetting">Concrete type which implements <see cref="ISetting"/></typeparam>
/// <param name="optionsTransformer">
/// a <see cref="DbContextOptionsTransformer{}"/> which configures your <see cref="DbContextOptions{}"/>. eg.
/// <code>
/// dbContextOptions => dbContextOptions.UseNpgsql(builder.Configuration.GetConnectionString("Default"))
/// </code>
/// </param>
/// <returns>The <see cref="IConfigurationBuilder"/></returns>
public static IConfigurationBuilder AddDbSet<TDbContext, TSetting>(this IConfigurationBuilder builder, DbContextOptionsTransformer<TDbContext> optionsTransformer)
where TDbContext : DbContext, ISettingsDbContext<DbSet<TSetting>, TSetting>, ISettingsDbContextFactory<TDbContext>
where TSetting : class, ISetting
{
var options = optionsTransformer(new DbContextOptionsBuilder<TDbContext>()).Options;
var configurationSource = new EntityFrameworkCoreDbSetConfigurationSource<TDbContext, TSetting>()
{
DbContextFactory = () => TDbContext.Create(options)
};
return builder.Add(configurationSource);
}
}