Created
December 27, 2018 11:05
-
-
Save henkmollema/fa4ef9a15167b8aad6aa09028f849cd1 to your computer and use it in GitHub Desktop.
MediatR generic dispatch
This file contains 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
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using MediatR; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace ConsoleApp3 | |
{ | |
public class Program | |
{ | |
private static async Task Main(string[] args) | |
{ | |
var services = new ServiceCollection(); | |
services.AddMediatR(); | |
var sp = services.BuildServiceProvider(); | |
using (var scope = sp.CreateScope()) | |
{ | |
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>(); | |
var foo = new Foo(); | |
await mediator.Publish(foo); | |
} | |
Console.WriteLine("Done"); | |
Console.ReadKey(); | |
} | |
} | |
public class Foo : INotification { } | |
public class FooHandler : INotificationHandler<Foo> | |
{ | |
public Task Handle(Foo notification, CancellationToken cancellationToken) | |
{ | |
Console.WriteLine($"Handler: {GetType().Name}"); | |
return Task.CompletedTask; | |
} | |
} | |
public class GenericHandler<TNotification> : INotificationHandler<TNotification> | |
where TNotification : INotification | |
{ | |
public Task Handle(TNotification notification, CancellationToken cancellationToken) | |
{ | |
Console.WriteLine($"Hander: {GetType().Name} where TNotification : {GetType().GetGenericArguments()[0].Name}"); | |
return Task.CompletedTask; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where does
ServiceCollection
object come from?