Last active
February 17, 2018 13:00
-
-
Save bvli/7d491fbf575c6aa05722ef348af37dae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface ICommand | |
{ | |
} | |
interface ICommandBus | |
{ | |
Task Send<TCommand>(TCommand command) where TCommand : ICommand; | |
} | |
interface ICommandHandler<TCommand> where TCommand : ICommand | |
{ | |
Task Handle(TCommand command); | |
} | |
class MyCommand : ICommand | |
{ | |
} | |
class MyCommandHandler : ICommandHandler<MyCommand> | |
{ | |
private readonly IHttpContextAccessor _context; | |
public MyCommandHandler(IHttpContextAccessor context) | |
{ | |
_context = context; | |
} | |
public async Task Handle(MyCommand command) | |
{ | |
await _context.HttpContext.Response.WriteAsync("Hej fra mig!"); | |
} | |
} | |
class CommandBus : ICommandBus | |
{ | |
private readonly IServiceProvider _services; | |
public CommandBus(IServiceProvider services) | |
{ | |
_services = services; | |
} | |
public async Task Send<TCommand>(TCommand command) where TCommand : ICommand | |
{ | |
var handler = _services.GetService<ICommandHandler<TCommand>>(); | |
await handler.Handle(command); | |
} | |
} | |
class CommandHandlerMiddleware | |
{ | |
public CommandHandlerMiddleware(RequestDelegate next) | |
{ | |
} | |
public async Task InvokeAsync(HttpContext context, ICommandBus bus) | |
{ | |
await bus.Send(new MyCommand()); | |
} | |
} | |
class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddScoped<ICommandBus, CommandBus>(); | |
services.AddScoped<ICommandHandler<MyCommand>, MyCommandHandler>(); | |
} | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
app.UseDeveloperExceptionPage(); | |
app.UseMiddleware<CommandHandlerMiddleware>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment