Skip to content

Instantly share code, notes, and snippets.

@henkmollema
Created December 27, 2018 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henkmollema/fa4ef9a15167b8aad6aa09028f849cd1 to your computer and use it in GitHub Desktop.
Save henkmollema/fa4ef9a15167b8aad6aa09028f849cd1 to your computer and use it in GitHub Desktop.
MediatR generic dispatch
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;
}
}
}
@demos666
Copy link

where does ServiceCollection object come from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment