首页 > 解决方案 > 如何解析在 ConfigureService 中注册的服务并在 .NET Core 3.0 中的 Autofac ConfigureContainer 方法中使用

问题描述

我的挑战是解决IHttpContextAccessor我在ConfigureServices方法中注册的服务,并使用它在方法上使用 Autofac 注册实例ConfigureContainer。但是随着在 .net core 3.0 中使用 Autofac 的新方法,我发现这样做真的很有挑战性。我尝试的方法如下;

        public void ConfigureContainer(ContainerBuilder builder)
        {
            var container = builder.Build();

            var httpContextAccessor = container.Resolve<IHttpContextAccessor>();
            var executionContextAccessor = new ExecutionContextAccessor(httpContextAccessor);

            ServicesAutofacExtensions.RegisterServicesWithAutofac(executionContextAccessor, Configuration, _loggerForApi);
        }

但是当我运行时它会抛出这个错误

访问 Microsoft.Extensions.Hosting 服务时出错。在没有应用程序服务提供商的情况下继续。错误:Build() 或 Update() 只能在 ContainerBuilder 上调用一次。

现在我知道在文档中,它说 ContainerBuilder 不应该以这种方法构建,工厂会自动处理这个问题。但是我该如何解析 IHttpContextAccessor 以在 ConfigureContainer 中使用它?我已经搜索并研究了可能的解决方案,但没有找到。请帮忙。

标签: c#autofac.net-core-3.0

解决方案


推荐阅读