版本v2.4.5.724中的Autofac ServiceLocator问题

时间:2011-03-25 00:30:38

标签: autofac

我刚刚升级到MVC 3,同样需要升级Autofac。

以下代码正常运行,但现在因此错误而失败 -

  

此解析操作已经存在   结束。注册组件时   使用lambdas,IComponentContext   lambda的'c'参数不能   存储。相反,要么解决   IComponentContext再次来自'c',或   解决一个Func<>基于工厂   从。

创建后续组件
    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);
    }

我应该如何重新注册IServiceLocator?

我查看了问题autofac registration issue in release v2.4.5.724的答案,但我仍感到困惑。

1 个答案:

答案 0 :(得分:1)

我真的应该阅读Nick的错误信息,答案就在信息中。

修复!!

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