1
votes

I have the following configuration in Autofac:

builder.Register<ServiceFactory>(x => y => x.Resolve<IComponentContext>().Resolve(y));  

With this configuration I get the error:

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

If I use the following than it works:

builder.Register<ServiceFactory>(x => {
  IComponentContext context = x.Resolve<IComponentContext>();
  return y => context.Resolve(y);
});    

Can't this configuration be made in one code line?

What am I missing?

1
You aren't missing anything. The component context can't be resolved from within the inner lambda. It has to be resolved outside, and used within.user47589

1 Answers

-1
votes

Your first configuration looks quite similar to the second but it differ on when IComponentContext is resolved.

Let me restructure a little bit your first configuration without changing logic.

builder.Register<ServiceFactory>(x => 
{ 
    return y => x.Resolve<IComponentContext>().Resolve(y)
});  

In the first example, you are registering lambda which

  1. Returns lambda which:

    1.1 Resolve IComponentContext

    1.2 Call Resolve on IComponentContext instance and return result

Let's compare it to the second configuration.

builder.Register<ServiceFactory>(x => {
  IComponentContext context = x.Resolve<IComponentContext>();
  return y => context.Resolve(y);
});    

In the second example, you are registering lambda which

  1. Resolve IComponentContext and assign it to variable 'context'

  2. Returns lambda which captures variable context and:

    2.1 Call Resolve on variable context and return result

So it differs on moment of resolving IComponentContext.