Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How not to bootstrap MediatR and Autofac, as it will never release inner dependencies... Pretty much follows this: https://github.com/jbogard/MediatR/blob/master/samples/MediatR.Examples.Autofac/Program.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Autofac;
using Autofac.Features.Variance;
using MediatR;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyModules(typeof(Program).Assembly);
var container = builder.Build();
var router = container.Resolve<IMediator>();
router.PublishAsync(new MyMessage()).Wait();
router.PublishAsync(new MyMessage()).Wait();
}
}
public class MyMessage : IAsyncNotification { }
public class ConcreteHandler :
IAsyncNotificationHandler<MyMessage>,
IDisposable
{
private readonly SomeDependency _dependency;
public ConcreteHandler(SomeDependency dependency)
{
_dependency = dependency;
}
public async Task Handle(MyMessage message)
{
await _dependency.DoWorkAsync();
}
public void Dispose()
{
Console.WriteLine("I am being released");
}
}
public class SomeDependency : IDisposable
{
public Task DoWorkAsync()
{
Console.WriteLine("Doing work with underlying connection");
return Task.FromResult(0);
}
public void Dispose()
{
Console.WriteLine("I'm cleaning the underlying connection.");
}
}
public class OurModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterSource(new ContravariantRegistrationSource());
builder.Register<SingleInstanceFactory>(ctx =>
{
var c = ctx.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
builder.Register<MultiInstanceFactory>(ctx =>
{
var c = ctx.Resolve<IComponentContext>();
return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
});
builder.RegisterType<Mediator>()
.As<IMediator>()
.SingleInstance();
builder.RegisterType<SomeDependency>();
builder.RegisterType<ConcreteHandler>()
.As<IAsyncNotificationHandler<MyMessage>>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment