As an ASP.NET Core MVC application grows across multiple business domains—such as Billing, HR, Reporting, or Inventory—dumping every controller, view, DTO, and service into a single web project creates tight coupling, slow incremental builds, and accidental cross-domain data dependencies. Yet jumping prematurely to microservices introduces distributed transactions, network hops, and operational overhead before domain boundaries are proven.
A modular monolith keeps deployment simple (a single ASP.NET Core MVC host, a single process, and clean transactional boundaries) while organizing each business domain into an independent class library or Razor Class Library (RCL). In ASP.NET Core MVC, ApplicationPartManager and IModuleDefinition (a clean module registration contract) let the host discover controllers, views, and services from each module assembly explicitly—without hardcoding every module's internals into Program.cs or allowing modules to bypass public contracts.
1. Architectural Blueprint & Module Boundary Rules
Plaintext
┌────────────────────────────────────────────────────────────────────────┐
│ ASP.NET Core MVC Host │
│ • Program.cs discovers & initializes IMvcModule implementations │
│ • ApplicationPartManager registers module assemblies & feature providers │
│ • Exposes shared cross-cutting contracts (IModuleEventBus / shared DTOs)│
└───────────┬───────────────────────────┬────────────────────────┬───────┘
│ │ │
▼ ▼ ▼
┌───────────────────────┐ ┌───────────────────────┐ ┌───────────────────────┐
│ Billing.Module │ │ Hr.Module │ │ Reporting.Module │
│ • Controllers (Billing)│ │ • Controllers (HR) │ │ • Controllers (Reports)│
│ • Views / TagHelpers │ │ • Views / TagHelpers │ │ • Read models / exports│
│ • Internal/private DB │ │ • Internal/private DB │ │ • Subscribes to events│
│ models & services │ │ models & services │ │ via public contracts│
└───────────────────────┘ └───────────────────────┘ └───────────────────────┘
Architectural Rule |
How It Is Enforced in C# / MVC |
Why It Matters |
Explicit Module Registration |
Each module exposes a public IMvcModule implementation (AddModuleServices + ConfigureApplicationParts). |
Keeps DI wiring encapsulated inside each module rather than leaking private services into Program.cs. |
Controller & View Discovery |
ApplicationPartManager registers module Assembly (and CompiledRazorAssemblyApplicationPart for RCLs).
|
MVC automatically discovers controllers, routing attributes, view components, and embedded/compiled views per module. |
Internal Encapsulation |
Keep domain entities, repositories, and internal handlers internal inside each module assembly. |
Prevents other modules from directly querying or mutating another module's internal persistence models. |
In-Process Integration via Contracts |
Modules communicate through shared integration contracts/events rather than direct internal references. |
Preserves clean boundaries today and makes future extraction into standalone services straightforward. |
2. Shared Module Contracts and In-Process Integration Bus
Create a lightweight shared contracts assembly or shared abstractions (such as IMvcModule and an in-process IModuleIntegrationPublisher / handler) that module projects reference without referencing each other's internal implementation assemblies.
C#
using Microsoft.AspNetCore.Mvc.ApplicationParts;
public interface IMvcModule
{
string Name { get; }
void ConfigureServices(IServiceCollection services, IConfiguration configuration);
void ConfigureApplicationParts(ApplicationPartManager partManager);
}
public interface IIntegrationEvent
{
Guid EventId { get; }
DateTimeOffset OccurredAtUtc { get; }
}
public interface IIntegrationEventHandler<in TEvent> where TEvent : IIntegrationEvent
{
Task HandleAsync(TEvent domainEvent, CancellationToken cancellationToken = default);
}
public interface IIntegrationEventPublisher
{
Task PublishAsync<TEvent>(TEvent integrationEvent, CancellationToken cancellationToken = default)
where TEvent : IIntegrationEvent;
}
public sealed class InMemoryIntegrationEventPublisher : IIntegrationEventPublisher
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<InMemoryIntegrationEventPublisher> _logger;
public InMemoryIntegrationEventPublisher(
IServiceProvider serviceProvider,
ILogger<InMemoryIntegrationEventPublisher> logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
}
public async Task PublishAsync<TEvent>(
TEvent integrationEvent,
CancellationToken cancellationToken = default)
where TEvent : IIntegrationEvent
{
ArgumentNullException.ThrowIfNull(integrationEvent);
var handlers = _serviceProvider.GetServices<IIntegrationEventHandler<TEvent>>().ToList();
_logger.LogInformation(
"Dispatching integration event {EventType} ({EventId}) to {HandlerCount} handler(s).",
typeof(TEvent).Name,
integrationEvent.EventId,
handlers.Count);
foreach (IIntegrationEventHandler<TEvent> handler in handlers)
{
await handler.HandleAsync(integrationEvent, cancellationToken);
}
}
}
public sealed record InvoiceSettledIntegrationEvent(
Guid EventId,
string InvoiceNumber,
decimal Amount,
string Currency,
DateTimeOffset OccurredAtUtc
) : IIntegrationEvent;
3. Implementing Two Independent Modules (Billing and AuditReporting)
Each module owns its controllers, models, and services. Notice how AuditReportingModule reacts to InvoiceSettledIntegrationEvent through IIntegrationEventHandler<InvoiceSettledIntegrationEvent> without referencing BillingModule's internal classes.
C#
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
// ============================================================================
// MODULE 1: BILLING MODULE
// ============================================================================
public sealed record SettleInvoiceRequest(
string InvoiceNumber,
decimal Amount,
string Currency = "USD"
);
public sealed record SettleInvoiceResponse(
Guid SettlementId,
string InvoiceNumber,
decimal Amount,
string Currency,
string Status,
DateTimeOffset SettledAtUtc
);
internal sealed class BillingSettlementService
{
private readonly IIntegrationEventPublisher _publisher;
public BillingSettlementService(IIntegrationEventPublisher publisher)
{
_publisher = publisher;
}
public async Task<SettleInvoiceResponse> SettleAsync(
SettleInvoiceRequest request,
CancellationToken cancellationToken)
{
string normalizedNumber = request.InvoiceNumber.Trim().ToUpperInvariant();
string normalizedCurrency = string.IsNullOrWhiteSpace(request.Currency)
? "USD"
: request.Currency.Trim().ToUpperInvariant();
DateTimeOffset nowUtc = DateTimeOffset.UtcNow;
var settlementId = Guid.NewGuid();
var integrationEvent = new InvoiceSettledIntegrationEvent(
EventId: Guid.NewGuid(),
InvoiceNumber: normalizedNumber,
Amount: decimal.Round(request.Amount, 2, MidpointRounding.AwayFromZero),
Currency: normalizedCurrency,
OccurredAtUtc: nowUtc);
await _publisher.PublishAsync(integrationEvent, cancellationToken);
return new SettleInvoiceResponse(
SettlementId: settlementId,
InvoiceNumber: normalizedNumber,
Amount: integrationEvent.Amount,
Currency: normalizedCurrency,
Status: "Settled",
SettledAtUtc: nowUtc);
}
}
[ApiController]
[Route("modules/billing/invoices")]
public sealed class BillingInvoicesController : ControllerBase
{
private readonly BillingSettlementService _settlementService;
internal BillingInvoicesController(BillingSettlementService settlementService)
{
_settlementService = settlementService;
}
[HttpPost("settle")]
public async Task<IActionResult> Settle(
[FromBody] SettleInvoiceRequest request,
CancellationToken cancellationToken)
{
if (request is null ||
string.IsNullOrWhiteSpace(request.InvoiceNumber) ||
request.Amount <= 0m)
{
return BadRequest(new ProblemDetails
{
Title = "Invalid Settlement Request",
Detail = "InvoiceNumber is required and Amount must be greater than zero.",
Status = StatusCodes.Status400BadRequest
});
}
SettleInvoiceResponse result = await _settlementService.SettleAsync(request, cancellationToken);
return Ok(result);
}
}
public sealed class BillingMvcModule : IMvcModule
{
public string Name => "Billing";
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<BillingSettlementService>();
}
public void ConfigureApplicationParts(ApplicationPartManager partManager)
{
var assembly = typeof(BillingMvcModule).Assembly;
if (!partManager.ApplicationParts.OfType<AssemblyPart>().Any(p => p.Assembly == assembly))
{
partManager.ApplicationParts.Add(new AssemblyPart(assembly));
}
}
}
// ============================================================================
// MODULE 2: AUDIT & REPORTING MODULE
// ============================================================================
public sealed record AuditLedgerEntry(
Guid EventId,
string InvoiceNumber,
decimal Amount,
string Currency,
DateTimeOffset RecordedAtUtc
);
internal sealed class AuditLedgerStore
{
private readonly ConcurrentQueue<AuditLedgerEntry> _entries = new();
public void Append(AuditLedgerEntry entry) => _entries.Enqueue(entry);
public IReadOnlyList<AuditLedgerEntry> GetAll() => _entries.ToArray();
}
internal sealed class InvoiceSettledAuditHandler : IIntegrationEventHandler<InvoiceSettledIntegrationEvent>
{
private readonly AuditLedgerStore _ledgerStore;
private readonly ILogger<InvoiceSettledAuditHandler> _logger;
public InvoiceSettledAuditHandler(
AuditLedgerStore ledgerStore,
ILogger<InvoiceSettledAuditHandler> logger)
{
_ledgerStore = ledgerStore;
_logger = logger;
}
public Task HandleAsync(
InvoiceSettledIntegrationEvent domainEvent,
CancellationToken cancellationToken = default)
{
var entry = new AuditLedgerEntry(
EventId: domainEvent.EventId,
InvoiceNumber: domainEvent.InvoiceNumber,
Amount: domainEvent.Amount,
Currency: domainEvent.Currency,
RecordedAtUtc: DateTimeOffset.UtcNow);
_ledgerStore.Append(entry);
_logger.LogInformation(
"Audit module recorded settled invoice {InvoiceNumber} ({Amount} {Currency}).",
entry.InvoiceNumber,
entry.Amount,
entry.Currency);
return Task.CompletedTask;
}
}
[ApiController]
[Route("modules/audit/ledger")]
public sealed class AuditLedgerController : ControllerBase
{
private readonly AuditLedgerStore _ledgerStore;
internal AuditLedgerController(AuditLedgerStore ledgerStore)
{
_ledgerStore = ledgerStore;
}
[HttpGet]
public IActionResult GetEntries()
{
IReadOnlyList<AuditLedgerEntry> entries = _ledgerStore.GetAll();
return Ok(new
{
Count = entries.Count,
Entries = entries
});
}
}
public sealed class AuditReportingMvcModule : IMvcModule
{
public string Name => "AuditReporting";
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<AuditLedgerStore>();
services.AddTransient<IIntegrationEventHandler<InvoiceSettledIntegrationEvent>, InvoiceSettledAuditHandler>();
}
public void ConfigureApplicationParts(ApplicationPartManager partManager)
{
var assembly = typeof(AuditReportingMvcModule).Assembly;
if (!partManager.ApplicationParts.OfType<AssemblyPart>().Any(p => p.Assembly == assembly))
{
partManager.ApplicationParts.Add(new AssemblyPart(assembly));
}
}
}
(Note: When each module lives in its own separate class library or Razor Class Library project, register typeof(BillingMvcModule).Assembly and typeof(AuditReportingMvcModule).Assembly—and if a module is an RCL containing compiled Razor views, CompiledRazorAssemblyApplicationPart is also discovered automatically by ApplicationPartManager.)
4. Host Discovery & ApplicationPartManager Wiring in Program.cs
The host maintains a curated list of IMvcModule instances (or discovers them from known module assemblies), registers their services, and applies ConfigureApplicationParts during AddControllersWithViews(...).
C#
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
public static class ModularHostExtensions
{
public static IServiceCollection AddMvcModules(
this IServiceCollection services,
IConfiguration configuration,
params IMvcModule[] modules)
{
services.AddSingleton<IReadOnlyList<IMvcModule>>(modules);
services.AddSingleton<IIntegrationEventPublisher, InMemoryIntegrationEventPublisher>();
foreach (IMvcModule module in modules)
{
module.ConfigureServices(services, configuration);
}
services.AddControllersWithViews()
.ConfigureApplicationPartManager(partManager =>
{
foreach (IMvcModule module in modules)
{
module.ConfigureApplicationParts(partManager);
}
});
return services;
}
}
[ApiController]
[Route("api/host/modules")]
public sealed class HostModulesController : ControllerBase
{
private readonly IReadOnlyList<IMvcModule> _modules;
private readonly ApplicationPartManager _partManager;
public HostModulesController(
IReadOnlyList<IMvcModule> modules,
ApplicationPartManager partManager)
{
_modules = modules;
_partManager = partManager;
}
[HttpGet]
public IActionResult GetLoadedModules()
{
return Ok(new
{
Modules = _modules.Select(m => m.Name).ToArray(),
ApplicationParts = _partManager.ApplicationParts
.Select(p => p.Name)
.Distinct(StringComparer.Ordinal)
.ToArray()
});
}
}
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMvcModules(
builder.Configuration,
new BillingMvcModule(),
new AuditReportingMvcModule());
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
public partial class Program { }
5. End-to-End Integration Testing with WebApplicationFactory<Program>
Testing against WebApplicationFactory<Program> verifies that controllers from each registered module are routed properly, module DI services resolve, and cross-module integration events flow end-to-end from Billing to Audit Reporting:
C#
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class ModularMonolithIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public ModularMonolithIntegrationTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task HostModulesEndpoint_ExposesRegisteredModulesAndApplicationParts()
{
using HttpClient client = _factory.CreateClient();
HttpResponseMessage response = await client.GetAsync("/api/host/modules");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string rawJson = await response.Content.ReadAsStringAsync();
using JsonDocument doc = JsonDocument.Parse(rawJson);
var moduleNames = doc.RootElement
.GetProperty("modules")
.EnumerateArray()
.Select(e => e.GetString())
.ToList();
Assert.Contains("Billing", moduleNames);
Assert.Contains("AuditReporting", moduleNames);
}
[Fact]
public async Task SettleInvoiceInBillingModule_PublishesEventToAuditReportingModule()
{
using HttpClient client = _factory.CreateClient();
string invoiceNumber = $"INV-{Guid.NewGuid():N}"[..14].ToUpperInvariant();
HttpResponseMessage settleResponse = await client.PostAsJsonAsync(
"/modules/billing/invoices/settle",
new SettleInvoiceRequest(invoiceNumber, 950.00m, "USD"));
Assert.Equal(HttpStatusCode.OK, settleResponse.StatusCode);
SettleInvoiceResponse? settled = await settleResponse.Content.ReadFromJsonAsync<SettleInvoiceResponse>();
Assert.NotNull(settled);
Assert.Equal("Settled", settled.Status);
HttpResponseMessage ledgerResponse = await client.GetAsync("/modules/audit/ledger");
Assert.Equal(HttpStatusCode.OK, ledgerResponse.StatusCode);
string ledgerJson = await ledgerResponse.Content.ReadAsStringAsync();
Assert.Contains(invoiceNumber, ledgerJson);
}
}
6. Conclusion
Structuring an ASP.NET Core MVC application as a Modular Monolith using ApplicationPartManager and explicit IMvcModule contracts gives you clean domain separation, encapsulated internals, and simple single-host deployment without premature distributed-systems complexity. Each module owns its MVC controllers, views, and DI registrations, communicates across boundaries via well-defined integration contracts, and remains straightforward to test and evolve as your domain requirements grow.
Join the conversation! Your thoughts help the community grow.