在Castle Windsor中为所有接口实现注册拦截器 [英] Registering an Interceptor For All Interface Implementations in Castle Windsor
问题描述
我对Castle Windsor还是陌生的,尤其是使用Interceptor,我想知道是否有可能在特定接口的所有实现中注册Interceptor,而无需依次指定每个实现。例如,我有一个名为 IComponent
的接口,该接口将由许多类实现。我编写了一个 ComponentInterceptor
类,以在这些类执行了特定方法后对其执行操作。我想做类似的事情:
_container.Register(
Component.For< IComponent>()
.Interceptors( ComponentInterceptor)
.LifestyleSingleton())
要做:
_container.Register(
Component.For< IComponent>()
.ImplementedBy< ComponentA>()
.Interceptors( ComponentInterceptor)
.LifestyleSingleton()),
_container.Register(
Component.For< IComponent>()
。 ImplementedBy< ComponentB>()
.Interceptors( ComponentInterceptor)
.LifestyleSingleton())
公共类MyContributeComponentConstruct:IContributeComponentModelConstruction
{
public void ProcessModel(IKernel kernel,ComponentModel model)
{
if(model.Services.Any(s => s == typeof(IComponent))))
{
model.Interceptors.Add(InterceptorReference.ForType< ComponentInterceptor>( ));
}
}
}
,然后添加温莎城堡容器
container.Kernel.ComponentModelBuilder.AddContributor(new MyContributeComponentConstruct());
I'm fairly new to Castle Windsor and in particular using Interceptors and am wondering if it is possible to register an Interceptor across all implementations of a particular interface without specifying each implementation in turn. For example, I have an interface called IComponent
which will be implemented by a number of classes. I have a ComponentInterceptor
class written to act on these classes when they have executed a particular method. I would like to do something like:
_container.Register(
Component.For<IComponent>()
.Interceptors("ComponentInterceptor")
.LifestyleSingleton())
Rather than having to do:
_container.Register(
Component.For<IComponent>()
.ImplementedBy<ComponentA>()
.Interceptors("ComponentInterceptor")
.LifestyleSingleton()),
_container.Register(
Component.For<IComponent>()
.ImplementedBy<ComponentB>()
.Interceptors("ComponentInterceptor")
.LifestyleSingleton())
I found another approach, I wanted to register this interceptor for all components being registered and do this hopefully minimal fuss. To do this I follow this article and created a new class like this:
public class MyContributeComponentConstruct : IContributeComponentModelConstruction
{
public void ProcessModel(IKernel kernel, ComponentModel model)
{
if (model.Services.Any(s => s == typeof(IComponent)))
{
model.Interceptors.Add(InterceptorReference.ForType<ComponentInterceptor>());
}
}
}
and then add this contribute with the Castle Windsor container
container.Kernel.ComponentModelBuilder.AddContributor(new MyContributeComponentConstruct ());
这篇关于在Castle Windsor中为所有接口实现注册拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!