开发者

How can an interceptor be added to a Typed Factory Facility factory method in Castle Windsor

I'm using a Typed Factory Facility in Castle Windsor. I want to get a callback when a factory method generates an instance of what it is supposed to create in order to wire up the instance for property change notification. This way I won't need to ensure this "post-creation" step is called after calling the factory method, instead giving this responsibility to the factory.

Is there a way, either using the Typed Factory Facil开发者_开发知识库ity or some other Castle feature to register a callback on the generated factory or create an interceptor on the factory which is used to perform the callback?


You can probably solve this by creating a Facility by deriving from AbstractFacility. Register to the Kernel.ComponentCreated event and check whether the created component needs the property changed notification. If so register.

You can use the ComponentDestroyed event to make sure you also nicely unregister. Below a code snippet I use to auto register view models with Caliburn.Micro's event aggregator

class EventRegistrationFacility : AbstractFacility
{
    private IEventAggregator _eventAggregator;

    protected override void Init()
    {
        Kernel.ComponentCreated += ComponentCreated;
        Kernel.ComponentDestroyed += ComponentDestroyed;
    }

    void ComponentCreated(Castle.Core.ComponentModel model, object instance)
    {
        if (!(instance is IHandle)) return;
        if (_eventAggregator == null) _eventAggregator = Kernel.Resolve<IEventAggregator>();
        _eventAggregator.Subscribe(instance);
    }

    void ComponentDestroyed(Castle.Core.ComponentModel model, object instance)
    {
        if (!(instance is IHandle)) return;
        if (_eventAggregator == null) return;
        _eventAggregator.Unsubscribe(instance);
    }

}

Kind regards, Marwijn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜