https://github.com/sergi0martin/openmediator
Alternative for those who do not want to pay for a mediator implementation.
https://github.com/sergi0martin/openmediator
csharp mediator mediator-design-pattern mediator-pattern
Last synced: 9 months ago
JSON representation
Alternative for those who do not want to pay for a mediator implementation.
- Host: GitHub
- URL: https://github.com/sergi0martin/openmediator
- Owner: Sergi0Martin
- License: apache-2.0
- Created: 2025-04-06T14:21:54.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-04-13T18:17:01.000Z (9 months ago)
- Last Synced: 2025-04-15T15:16:28.536Z (9 months ago)
- Topics: csharp, mediator, mediator-design-pattern, mediator-pattern
- Language: C#
- Homepage: https://www.nuget.org/packages/OpenMediator
- Size: 132 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://codecov.io/gh/Sergi0Martin/OpenMediator)
# OpenMediator
Alternative for those who do not want to pay for a mediator implementation.
### Configuration
In your Program.cs call AddOpenMediator
```csharp
services.AddOpenMediator(config =>
{
config.RegisterCommandsFromAssemblies([Assembly.GetExecutingAssembly()]);
});
```
### Usage
1 Create commands
```csharp
public record CreateUserCommand(int Id, string Name) : ICommand;
```
2 Call MediatorBus
```csharp
[ApiController]
[Route("api/user")]
public class UserController(IMediatorBus _mediator) : ControllerBase
{
[HttpPost()]
public async Task CreateUser()
{
var command = new CreateUserCommand(1, "UserTest");
await _mediator.SendAsync(command);
return Ok();
}
}
```
3 Define your use case
```csharp
public record CreateUserCommandHandler(ILogger _logger) : ICommandHandler
{
public async Task HandleAsync(CreateUserCommand command)
{
// Simulate some work
await Task.Delay(1000);
}
}
```
### Middleware Configuration
Also you can configure and execute custom middlewares before or after the command.
1. Define your middleware by implementing the `IMiddleware` interface:
```csharp
public class CustomMediatorMiddleware() : IMediatorMiddleware
{
public async Task ExecuteAsync(TCommand command, Func next)
where TCommand : ICommand
{
// Do something before the command
await Task.Delay(500);
await next();
// Do something after the command
await Task.Delay(500);
}
public async Task ExecuteAsync(TCommand command, Func> next)
where TCommand : ICommand
{
// Do something before the command
await Task.Delay(500);
var result = await next();
// Do something after the command
await Task.Delay(500);
return result;
}
}
```
2. Register your middlewares in the `AddOpenMediator` method:
```csharp
services.AddOpenMediator(config =>
{
config.RegisterCommandsFromAssemblies([Assembly.GetExecutingAssembly()]);
config.RegisterMiddleware();
});
```