【问题标题】:System.ObjectDisposedException: This resolve operation has already endedSystem.ObjectDisposedException:此解析操作已结束
【发布时间】:2019-02-04 16:15:03
【问题描述】:

我在 Autofac 中有如下配置:

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

使用此配置我得到错误:

System.ObjectDisposedException:此解析操作已经 结束了。 使用 lambda 注册组件时,无法存储 lambda 的 IComponentContext 'c' 参数。 相反,要么从 'c' 再次解析 IComponentContext,要么解析基于 Func 的工厂以从中创建后续组件。

如果我使用以下内容,则可以:

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

这个配置不能在一行代码中完成吗?

我错过了什么?

【问题讨论】:

  • 您没有遗漏任何东西。无法从内部 lambda 中解析组件上下文。它必须在外部解决,并在内部使用。

标签: c# autofac


【解决方案1】:

您的第一个配置看起来与第二个配置非常相似,但在解决 IComponentContext 时有所不同。

让我在不改变逻辑的情况下稍微重构一下你的第一个配置。

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

在第一个示例中,您正在注册 lambda

  1. 返回 lambda,其中:

    1.1 解析IComponentContext

    1.2 在 IComponentContext 实例上调用 Resolve 并返回结果

让我们将其与第二种配置进行比较。

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

在第二个示例中,您正在注册 lambda

  1. 解析 IComponentContext 并将其分配给变量 'context'

  2. 返回捕获变量上下文的 lambda 和:

    2.1 对变量上下文调用Resolve并返回结果

所以它在解析 IComponentContext 的时刻有所不同。

【讨论】:

    猜你喜欢
    • 2019-04-02
    • 2017-06-21
    • 2016-01-19
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多