首页 > 解决方案 > c# Unity 5.11.10 依赖注入 StackOverflow 异常

问题描述

我刚刚将 Unity 包升级到最新版本,当我注册 2 个 dto 对象映射器时,我得到了一个可能的循环依赖“Stackoverflow”异常。

UnityConfig.cs

public static void RegisterTypes()
{
        ...
        Container.RegisterType<IResultMapper<Object1>, Object1DtoObject1Mapper>(new PerResolveLifetimeManager(), new InjectionMethod(nameof(IBaseMapper.Init)));
        Container.RegisterType<IResultMapper<Object2>, Object2DtoObject2Mapper>(new PerResolveLifetimeManager(), new InjectionMethod(nameof(IBaseMapper.Init)));
}

Object2DtoObject2Mapper.cs

public class Object2DtoObject2Mapper: ResultMapperConfigurator<Object2Dto, Object2>
{
    #region Public Methods

    /// <summary>
    /// Initialize the mapping configuration.
    /// </summary>
    public override void Init()
    {
        Property(dto => dto.Id, entity => entity.Id);
        

        Collection(dto => dto.property, entity => entity.property, Object1Mapper);
        

        Validate();
    }

    #endregion

    #region Public Properties

    #region Mappers

    //error occurs here
    [Dependency]
    public Object1DtoObject1Mapper Object1Mapper { get; set; }

    #endregion

    #endregion
}

Object1DtoObject1Mapper.cs

public class Object1DtoObject1Mapper: ResultMapperConfigurator<Object1Dto, Object1>
{
    #region Public Methods

    /// <summary>
    /// Initialize the mapping configuration.
    /// </summary>
    public override void Init()
    {
        Property(dto => dto.Id, entity => entity.Id);
        

        Collection(dto => dto.property, entity => entity.property, Object2Mapper);
        

        Validate();
    }

    #endregion

    #region Public Properties

    #region Mappers

    //error occurs here
    [Dependency]
    public Object2DtoObject2Mapper Object2Mapper { get; set; }

    #endregion

    #endregion
}

在每个 dto 对象映射器中,都有另一个用于映射适当属性或集合的依赖项。上面的代码使用以前版本的 Unity (4.0.1) 没有产生错误。谁能告诉我如何在每个映射器中注入“Object1DtoObject1Mapper”和“Object2DtoObject2Mapper”?

标签: c#unity-container

解决方案


推荐阅读