using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
var services = new ServiceCollection();
services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssemblies(typeof(DisableLdapAccountCommand).Assembly);
services.AddTransient<IRequestHandler<DisableLdapAccountCommand, Result>, DisableLdapAccountHandler>();
services.AddTransient<IRequestHandler<EnableLdapAccountCommand, Result>, EnableLdapAccountHandler>();
var provider = services.BuildServiceProvider();
var mediator = provider.GetRequiredService<IMediator>();
var correlationId = Guid.NewGuid().ToString();
List<IWorkflowCommand> steps = new List<IWorkflowCommand>();
steps.Add(new DisableLdapAccountCommand
SAMAccountName = "tory.berra",
CorrelationId = correlationId,
steps.Add(new EnableLdapAccountCommand
SAMAccountName = "tory.berra",
CorrelationId = correlationId,
var results = new List<IResult>();
foreach (var step in steps)
var response = await mediator.Send(step);
results.Add((IResult)response);
Console.WriteLine($"Global unhandled exception. {e.Message}");
public interface IWorkflowCommand
public string CorrelationId { get; set; }
public class DisableLdapAccountCommand : IRequest<Result>, IWorkflowCommand
public string SAMAccountName { get; set; }
public string CorrelationId { get; set; }
public class EnableLdapAccountCommand : IRequest<Result>, IWorkflowCommand
public string SAMAccountName { get; set; }
public string CorrelationId { get; set; }
public class DisableLdapAccountHandler : IRequestHandler<DisableLdapAccountCommand, Result>
public Task<Result> Handle(DisableLdapAccountCommand request, CancellationToken cancellationToken)
return Task.FromResult(Result.SuccessWithMessage("DisableLdapAccountHandler Worked"));
public class EnableLdapAccountHandler : IRequestHandler<EnableLdapAccountCommand, Result>
public Task<Result> Handle(EnableLdapAccountCommand request, CancellationToken cancellationToken)
throw new Exception("Boom");
return Task.FromResult(Result.SuccessWithMessage("EnableLdapAccountHandler Worked"));
public class GenericRequestExceptionHandler<TRequest, TResponse, TException> : IRequestExceptionHandler<TRequest, TResponse, TException>
where TRequest : IWorkflowCommand
where TException : Exception
RequestExceptionHandlerState<TResponse> state,
CancellationToken cancellationToken = new CancellationToken())
Console.WriteLine("GenericRequestExceptionHandler translating exception to error.");
var translatedResponse = Result.Error("Unhandled exception.");
state.SetHandled((TResponse)translatedResponse);
return Task.CompletedTask;