使用 IoC 容器作为某些服务的服务定位器来获得机会创建子作用域

问题描述

我想使用 DryIoC 作为服务定位器,即将容器实例注入某个服务以获得机会创建子范围。

internal abstract class BaseService<TEntity,T> : Idisposable
    where TEntity : class,IEntity<T>
    where T : notnull
{
    **protected bool isParallel = false;**

    protected DataContext Context
        => **this.isParallel
         ? this.resolver.Value.Resolve<DataContext>()
         :** this.current.Context;

    **private readonly Lazy<IResolverContext> resolver;**

    **private bool IsReadOnly => this.isParallel;**

    protected BaseService(**IContainer container,** ICurrentDataContext current,IDeletingStrategy<TEntity> delete)
    {
        this.strategies =
            new ()
            {
                Delete = delete
            };

        **this.resolver = new Lazy<IResolverContext>(() => container.OpenScope());**

        this.current = current;
    }

    private void ReadOnlyCheck()
    {
        **if (this.IsReadOnly)
        {
            throw
              new NotSupportedException("Todo");
        }**
    }

    protected virtual void dispose(bool disposing)
    {
        if (this.wasdisposed)
        {
            return;
        }

        if (disposing)
        {
            **this.resolver.Value.dispose();**
        }

        this.wasdisposed = true;
    }
}

当我调用任何 CRUD 方法时,会抛出以下异常:

DryIoc.ContainerException:“代码:Error.ContainerIsdisposed; 消息:容器已释放,不应使用:“容器的范围为 {Isdisposed=true,Name=null} 使用带有 {TrackingdisposableTransients} 和不带 {ThrowOnRegisteringdisposableTransient,VariantGenericTypesInResolvedCollection} 的规则 使用 FactorySelector=SelectLastRegisteredFactory 与 Made={FactoryMethod=ConstructorWithResolvableArguments,PropertiesAndFields=} 已被处置! 您可以通过以下方式将 dispose 堆栈跟踪包含在消息中: container.With(rules => rules.WithCaptureContainerdisposeStackTrace())""

但是如果我删除 bold 元素,它会起作用。

解决方法

仅凭提供的代码还是很难找到问题所在。

我猜想传递给 container 构造函数并用于延迟创建作用域解析器的 BaseService 参数在您尝试创建实际解析器时已被释放。

此外,传递给 BaseMessage 的容器已经是每个异常消息的作用域容器,可能不是您所期望的。

您可以添加异常中提到的规则 container.With(rules => rules.WithCaptureContainerDisposeStackTrace()) 以获取容器被处理的实际位置。