从UnityContainer中检索实例化的类型

时间:2018-03-05 15:52:08

标签: c# unity-container

(使用Unity 4.0.1)

给定一个UnityContainer对象,有没有办法检索容器实例化到目前为止的所有对象?例如。

之类的东西

Date.now()

或者更好的是,根据从给定类型派生的那些进行过滤:

IEnumerable<object> instantiatedObjects = unityContainer.GetAllInstantiatedObjects();

1 个答案:

答案 0 :(得分:0)

遵循RB's suggestion,以下方法implements a custom Unity extension,其策略在PostInitializtion上保留对每个实例化对象的引用。

N.B。以下代码仅供参考,并非旨在用于线程安全/异常安全等。

首先,实现Extension类和它依赖的其他类。

public class ObjectContainer
{
    private readonly List<object> _instantiatedObjects = new List<object>();
    public void Add(object instantiatedObject)
    {
        _instantiatedObjects.Add(instantiatedObject);
    }
    public IEnumerable<object> GetInstantiatedObjects()
    {
        return _instantiatedObjects;
    }
    public IEnumerable<T> GetInstantiatedObjects<T>()
    {
        return GetInstantiatedObjects().OfType<T>();
    }
}

public class InstantiatedObjectsStrategy : BuilderStrategy
{
    private readonly ObjectContainer _objectContainer;
    public InstantiatedObjectsStrategy(ObjectContainer objectContainer)
    {
        _objectContainer = objectContainer;
    }
    public override void PostBuildUp(IBuilderContext context)
    {
        _objectContainer.Add(context.Existing);
    }
}

public class InstantiatedObjectsExtension : UnityContainerExtension
{
    private readonly ObjectContainer _objectContainer = new ObjectContainer();
    protected override void Initialize()
    {
        Context.Container.RegisterInstance(_objectContainer);
        Context.Strategies.Add(new InstantiatedObjectsStrategy(_objectContainer),
            UnityBuildStage.PostInitialization);
    }
}

扩展可以在创建后立即添加到UnityContainer:

IUnityContainer container = new UnityContainer();
container.AddNewExtension<InstantiatedObjectsExtension>();

然后可以在稍后阶段从容器中检索实例化对象,如下所示:

IEnumerable<object> instantiatedObjects = container.Resolve<ObjectContainer>().GetInstantiatedObjects();
IEnumerable<Foo> instantiatedFoos = container.Resolve<ObjectContainer>().GetInstantiatedObjects<Foo>();