The author provides an example of how to use MediatR in a console application using Autofac:
var builder = new ContainerBuilder();
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof (IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Ping).Assembly).AsImplementedInterfaces();
builder.RegisterInstance(Console.Out).As<TextWriter>();
var lazy = new Lazy<IServiceLocator>(() => new AutofacServiceLocator(builder.Build()));
var serviceLocatorProvider = new ServiceLocatorProvider(() => lazy.Value);
builder.RegisterInstance(serviceLocatorProvider);
I took this example and attempted to make it work with ASP MVC 5 and the Autofac.Mvc5 package:
var builder = new ContainerBuilder();
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof(IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(AddPostCommand).Assembly).AsImplementedInterfaces();
builder.RegisterControllers(typeof(HomeController).Assembly);
var container = builder.Build();
var lazy = new Lazy<IServiceLocator>(() => new AutofacServiceLocator(container));
var serviceLocatorProvider = new ServiceLocatorProvider(() => lazy.Value);
builder.RegisterInstance(serviceLocatorProvider);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
When I run the web application, I get an error page telling me that the ServiceLocationProvider dependency has not been registered. What am I doing wrong?
I suspect that the problem is due to the fact that I am registering the ServiceLocatorProvider instance after calling Build - in the author's example, the Build method is invoked afterwards thanks to Lazy<>. I do not know how to work around this, though.
You cannot call Builder.Build before you finish registering types.
in your example you are calling Builder.Build before you call builder.RegisterInstance which explains why it cannot infer the type at runtime.
I came up with this after hitting the same issue today, but it is work in progress as it doesnt resolve my implementations yet...
I am creating the container in a separate
Lazy<T>and passing that around.While this builds and the site loads, it cannot infer which handler to use for the request in my controller action...
which raises the exception...
This is using the same convention based registration provided in the Autofac examples project included in MediatR, and i have also tried registering it explicitly....
I will update when i get it working. Please do the same if you figure it out before i do.