Francesc Castells
Francesc Castells

Reputation: 2857

Understanding Autofac configuration for Mediatr

I'm trying to configure Mediatr with Autofac. The documentation shows how to configure it, but I don't understand how the ServiceFactory registration works.

The registration is as follows:

builder.Register<ServiceFactory>(ctx =>
{
   var c = ctx.Resolve<IComponentContext>();
   return t => c.Resolve(t);
});

And ServiceFactory is a delegate:

/// <summary>
/// Factory method used to resolve all services. For multiple instances, it will resolve against <see cref="IEnumerable{T}" />
/// </summary>
/// <param name="serviceType">Type of service to resolve</param>
/// <returns>An instance of type <paramref name="serviceType" /></returns>
public delegate object ServiceFactory(Type serviceType);

My understanding is that when resolving ServiceFactory, Autofac will resolve the anonymous function:

 t=>c.Resolve(t)

but I don't understand why IComponentContext is resolved from ctx, given that ctx is already an IComponentContext.

So what difference would it make to register it this way:

builder.Register<ServiceFactory>(ctx =>
{
   return t => ctx.Resolve(t);
});

Upvotes: 2

Views: 503

Answers (1)

Cyril Durand
Cyril Durand

Reputation: 16187

My understanding is that when resolving ServiceFactory, Autofac will resolve the anonymous function

You are right.

but I don't understand why IComponentContext is resolved from ctx, given that ctx is already an IComponentContext.

You can't use ctx because this context will be disposed when the delegate will be invoked. If you do

builder.Register<ServiceFactory>(ctx =>
{
    return t => ctx.Resolve(t);
});

You will have a ObjectDisposedException when you invoke the ServiceFactory delegate.

System.ObjectDisposedException: This resolve operation has already ended. When registering components using lambdas, the IComponentContext 'ctx' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'ctx', or resolve a Func<> based factory to create subsequent components from.

the ctx provided by the Register method is built only for the registration process and will be disposed at the end of it. That's why you have to resolve another IComponentContext to get one which will be alive the whole lifetime scope.

Upvotes: 2

Related Questions