【问题标题】:Autofac ServiceLocator issue in release v2.4.5.724版本 v2.4.5.724 中的 Autofac ServiceLocator 问题
【发布时间】:2011-07-22 14:04:04
【问题描述】:

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

以下代码可以运行,但现在失败并出现此错误 -

这个解析操作已经 结束了。注册组件时 使用 lambda,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的答案,但我还是一头雾水。

【问题讨论】:

    标签: autofac


    【解决方案1】:

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

    已修复!!

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

    【讨论】:

    • 很酷的东西 :) ... 在 MVC3 中,您可能会考虑删除自定义服务定位器并改用 DependencyResolver.Current
    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2016-04-04
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多