Skip to content

HubiBoar/Momolith

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Momolith

Release Status

Momolith Is a framework helping to create Modular Monolith Architecture.

This project and samples are still WORK IN PROGRESS.

Momolith.Modules

NuGet Version NuGet Downloads

Program.cs

var hostExtender = new WebAppExtender();

builder.AddModule(setup => DataLayerModule.Create(setup, sql))
    .Migrate(hostExtender);

var app = builder.Build();

await hostExtender.RunExtensionsAsync(app);

app.Run();

DataLayerModule.cs

public sealed class DataLayerModule : Module
{
    private readonly List<Func<IHost, Task>> _migrations;
    private readonly Action<DbContextOptionsBuilder>? _optionsAction;

    private DataLayerModule(
        ModuleSetup moduleSetup,
        Action<DbContextOptionsBuilder>? optionsAction)
        : base(moduleSetup)
    {
        _optionsAction = optionsAction;
        _migrations = [];
    }

    public static DataLayerModule Create(ModuleSetup setup, string sqlConnectionString)
    {
        return new DataLayerModule(setup, options => options.UseSqlServer(sqlConnectionString));
    }

    public void AddDbContextFactory<T>()
        where T : DbContext
    {
        Services.AddDbContextFactory<T>(_optionsAction);
        _migrations.Add(Migrate<T>);
    }

    public Task Migrate(IHost host)
    {
        return Task.WhenAll(_migrations.Select(x => x.Invoke(host)));
    }

    private static async Task Migrate<T>(IHost host)
        where T : DbContext
    {
        using var scope = host.Services.CreateScope();
        var context = scope.ServiceProvider.GetRequiredService<T>();

        await context.Database.MigrateAsync();
    }