0
votes

I have just upgraded to MVC 3 and likewise need to upgrade Autofac.

The following code was working, but now fails with this error -

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.

    public static IServiceLocator Locator;

    public class ServiceA : IServiceA
    {
    }

    public interface IServiceA
    {
    }

    [Test]
    public void TestAutofacServiceLocator()
    {
        // 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.
        var builder = new ContainerBuilder();

        builder.RegisterType<ServiceA>().As<IServiceA>();

        builder.Register(c => Locator = new AutofacServiceLocator(c)).As<IServiceLocator>().SingleInstance();

        var container = builder.Build();

        container.Resolve<IServiceLocator>();
        var x = Locator.GetInstance<IServiceA>();
        Assert.NotNull(x);
    }

How should I resgister IServiceLocator?

I looked at the answer to question autofac registration issue in release v2.4.5.724 but I'm still confused.

1

1 Answers

1
votes

I really should have read Nick's error message, the answer was in the message.

Fixed !!

builder.Register(c => Locator = new AutofacServiceLocator(c.Resolve())) .As().SingleInstance();