Этот пример доступен в следующем github Repo:
https://github.com/scheemelhout/console ... ode]public interface IQuery : IRequest;
public interface IQueryHandler : IRequestHandler
where TQuery : IQuery;
public class QueryResult
{
public TResult? Result { get; set; }
public bool Succeeded { get; set; }
public string? Error { get; set; }
}
< /code>
public class Pong { }
public class PingQuery : IQuery { }
< /code>
public class PingQueryHandler : IQueryHandler
{
public Task Handle(PingQuery query, CancellationToken cancellationToken)
{
Console.WriteLine($"'{GetType()}' is processing '{query.GetType()}'");
var response = new QueryResult
{
Result = new Pong(),
Succeeded = true,
};
return Task.FromResult(response);
}
}
< /code>
Я хотел бы создать поведение медиатр, которые могут вернуть неудачный запрос в некоторых обстоятельствах: < /p>
public class Behavior_1 : IPipelineBehavior
where TQuery : IRequest
{
public async Task Handle(TQuery query, RequestHandlerDelegate next, CancellationToken cancellationToken)
{
Console.WriteLine($"'{GetType()}' is processing '{query.GetType()}'");
// if (DoSomeValidation() == false)
// return new QueryResult { Succeeded = false, Error = "Validaton failed" };
var result = await next(cancellationToken);
return result;
}
private static bool DoSomeValidation() => false;
}
public class Behavior_2 : IPipelineBehavior
where TQuery : IQuery
{
public async Task Handle(TQuery query, RequestHandlerDelegate next, CancellationToken cancellationToken)
{
Console.WriteLine($"'{GetType()}' is processing '{query.GetType()}'");
if (DoSomeValidation() == false)
return new QueryResult { Succeeded = false, Error = "Validaton failed" };
var result = await next(cancellationToken);
return result;
}
private static bool DoSomeValidation() => false;
}
< /code>
Оба поведения зарегистрированы правильно: < /p>
services.AddMediatR(configuration =>
{
configuration.RegisterServicesFromAssembly(typeof(Program).Assembly);
configuration.AddOpenBehavior(typeof(Behavior_1));
configuration.AddOpenBehavior(typeof(Behavior_2));
});
[/code]
Когда я отправляю экземпляр Pingrequest , я вижу, что поведение_1 запускается, но поведение_2 не является:
Код: Выделить всё
'ConsoleApp1.Behavior_1`2[ConsoleApp1.PingQuery,ConsoleApp1.QueryResult`1[ConsoleApp1.Pong]]' is processing 'ConsoleApp1.PingQuery'
'ConsoleApp1.PingQueryHandler' is processing 'ConsoleApp1.PingQuery'
True
Process finished with exit code 0.
Подробнее здесь: https://stackoverflow.com/questions/796 ... in-mediatr
Мобильная версия