在基础 class 中创建递归 BuildUpAll 方法,未填写所有依赖属性

Creating a recursive BuildUpAll method in a base class not filling out all the dependency properties

我正在使用 Unity 进行依赖项注入,并且有一个相当大的 class 结构,每个级别都继承自基础 class。由于各种原因,我正在使用 Unity 的依赖属性功能,并试图创建一个单一的方法,该方法将向下遍历结构并构建所有对象,而无需我再手动管理该代码。我的基地 class 到目前为止看起来像这样

public class Base
{
    [Dependency]
    public IEventAggregator EventAggregator { get; set; }

    [Dependency]
    public ILoggerFacade LoggerFacade { get; set; }

    public void BuildUpDependencies(IUnityContainer container)
    {
        var currentType = this.GetType();

        container.BuildUp(this);

        PropertyInfo[] properties = currentType.GetProperties();

        foreach (var propertyInfo in properties)
        {
            var propertyType = propertyInfo.PropertyType;


            // if property type is part go one level further down unless it has an attribute of GetValidationMessagesIgnore
            if (TypeContainsBaseType(propertyType, typeof(Base)))
            {
                ((Base)propertyInfo.GetValue(this)).BuildUpDependencies(container);
            }
        }
    }
}

这对于构建由所有 classes 继承的 2 个依赖项非常有用,但这不会构建不在基础 class 中的任何依赖项。即

public class InterestingClass : Base
{
    [Dependency]
    public IRegionManager RegionManager { get; set; }
}

在这种情况下,InterestingClass 将构建 2 个基本依赖项,但 RegionManager 将保持为空。

我相信这是因为在 BuildUpDependencies 方法中,传递的 'this' 是 Base 类型而不是 InterestingClass 类型,但我不确定如何确保派生的 class 类型是传递给 BuildUp 方法。有没有更简单的方法来做到这一点?我怎样才能将正确的类型传递给 BuildUp 以将其传递给 BuildUp 所有正确的依赖项?

当所有其他方法都失败时,阅读文档通常会有所帮助。如果您引用 The Build Up documentation,则存在接受类型和对象的 BuildUp 重载。如果你更换

...
var currentType = this.GetType();

container.BuildUp(this);
...

...
var currentType = this.GetType();

container.BuildUp(currentType, this);
...

BuildUp 方法可以毫无问题地构建派生 类 中的所有内容。