PolePostgreSqlStartupConfigExtensions.cs
1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using Microsoft.EntityFrameworkCore;
using Pole.Core;
using Pole.Core.EventBus.EventStorage;
using Pole.Core.EventBus.Transaction;
using Pole.EventStorage.PostgreSql;
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Extensions.DependencyInjection
{
public static class PolePostgreSqlStartupConfigExtensions
{
public static StartupConfig AddEntityFrameworkEventStorage<TContext>(this StartupConfig config)
where TContext : DbContext
{
return config.AddEntityFrameworkEventStorage<TContext>(opt => { });
}
public static StartupConfig AddEntityFrameworkEventStorage<TContext>(this StartupConfig config, Action<EFOptions> configure)
where TContext : DbContext
{
if (configure == null) throw new ArgumentNullException(nameof(configure));
EFOptions eFOptions = new EFOptions();
configure(eFOptions);
Action<PostgreSqlOptions> postgreSqlOptionsConfig = postgreSqlOptions =>
{
postgreSqlOptions.DbContextType = typeof(TContext);
postgreSqlOptions.Schema = eFOptions.Schema;
using var scope = config.Services.BuildServiceProvider().CreateScope();
var provider = scope.ServiceProvider;
using var dbContext = (DbContext)provider.GetRequiredService(typeof(TContext));
postgreSqlOptions.ConnectionString = dbContext.Database.GetDbConnection().ConnectionString;
};
config.Services.Configure(postgreSqlOptionsConfig);
config.Services.AddScoped<IDbTransactionAdapter, PostgreSqlDbTransactionAdapter>();
config.Services.AddSingleton<IEventStorage, PostgreSqlEventStorage>();
config.Services.AddSingleton<IEventStorageInitializer, PostgreSqlEventStorageInitializer>();
return config;
}
}
}