Whilst I am a massive fan of MediatR, it feels strange to take it as a dependency on all my projects (even those that dont "dispatch" and are merely posting POCOs reference the marker interfaces).
What is the need therefore for marker interfaces in the first place, when the below code works with plain POCOs?
Is there any issues with removing the marker interfaces from Notification
and Request
?
Handler interfaces
public interface INotificationHandler<in TNotification> where TNotification : class
{
Task Handle(TNotification notification, CancellationToken cancellationToken);
}
public interface IRequestHandler<in TRequest, TResponse> where TRequest : class
{
Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
}
Plain POCO without marker interfaces
class TestNotification
{
public int UserId { get; set; }
public int Age { get; set; }
}
class TestRequest
{
public int UserId { get; set; }
}
Handlers
class TestRequestHandler : IRequestHandler<TestRequest, int>
{
public Task<int> Handle(TestRequest request, CancellationToken cancellationToken)
{
return Task.FromResult(request.UserId);
}
}
class TestNotificationHandler : INotificationHandler<TestNotification>
{
public Task Handle(TestNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine("hello");
return Task.CompletedTask;
}
}
Main
static void Main(string[] args)
{
_ = new TestNotificationHandler()
.Handle(new TestNotification(), CancellationToken.None);
var result = new TestRequestHandler()
.Handle(new TestRequest() { UserId = 111 }, CancellationToken.None)
.Result;
Console.WriteLine($"result is {result}");
}
C# fiddle
https://dotnetfiddle.net/HTkfh9
Aucun commentaire:
Enregistrer un commentaire