我正在开发一个使用 bbv EventBrokerExtension 库的应用程序。我想要完成的是,我想让通过容器实例化的实例与 EventBroker 统一注册。我计划通过 UnityContainerExtension 实现这一点并实现 IBuilderStrategy。问题是接口的方法似乎是为构造函数中的每个参数调用的。问题是当 Singleton 实例在构建对象时得到解决时,它们将被多次注册。
例如假设你有
class Foo(ISingletonInterface singleton){}
class Foo2(ISingletonInterface singleton){}
然后你通过统一解决它们
var container = new UnityContainer();
container.AddNewExtension<EventBrokerWireupStrategy>();
container.RegisterInstance<IEventBroker>(new EventBroker());
container.RegisterInstance(new Singleton());
var foo = container.Resolve<Foo>();
var foo2 = container.Resolve<Foo2>();
然后 UnityContainerExtension 将在同一个单例对象上调用 postbuildup。这是我对 UnityContainerExtension 的幼稚实现。
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.ObjectBuilder;
using bbv.Common.EventBroker;
using System.Collections.Generic;
namespace PFC.EventingModel.EventBrokerExtension
{
public class EventBrokerWireupExtension : UnityContainerExtension, IBuilderStrategy
{
private IEventBroker _eventBroker;
private List<object> _wiredObjects = new List<object>();
public EventBrokerWireupExtension(IEventBroker eventBroker)
{
_eventBroker = eventBroker;
}
protected override void Initialize()
{
Context.Strategies.Add(this, UnityBuildStage.PostInitialization);
}
public void PreBuildUp(IBuilderContext context)
{
}
public void PostBuildUp(IBuilderContext context)
{
if (!_wiredObjects.Contains(context.Existing))
{
_eventBroker.Register(context.Existing);
_wiredObjects.Add(context.Existing);
}
}
public void PreTearDown(IBuilderContext context)
{
}
public void PostTearDown(IBuilderContext context)
{
}
}
}