Dears, I have an interface IJob that has a method called ExecuteAsync and i want to intercept this method only but my derived classes may have many methods and i found the interceptor intercept them also. My question is, Is this possible with Castle Windsor and this is my registration
iocManager.IocContainer.Kernel.ComponentRegistered += (key, handler) =>
{
var implementationType = handler.ComponentModel.Implementation.GetTypeInfo();
if(ShouldIntercept(implementationType))
{
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuthenticateJobInterceptor)));
}
};
private static bool ShouldIntercept(Type type)
{
if (typeof(IJob).IsAssignableFrom(type))
{
return true;
}
return false;
}
Yes it is. There's a IProxyGenerationHook
interface that you can implement to control what gets intercepted. The tutorial I wrote a decade ago still (for better or worse) seems to be the best resource about it.
There's a couple ways to set it up in Windsor.
Ideally, if possible, you'd do it during registration, in your IWindsorInstaller
:
var yourHook = new YourHook();
container.Register(
Classes.FromThisAssembly()
.BasedOn<IJob>()
.LifestyleTransient()
.WithServiceBase()
.Configure(c =>
c.Interceptors<AuthenticateJobInterceptor>()
.Proxy.Hook(yourHook)));
Alternatively, if you want to keep your code similar to what it is now (I'd recommend wrapping in a ComponentModel construction contributor), you can do something like:
var options = handler.ComponentModel.ObtainProxyOptions();
options.Hook = yourHook; // InstanceReference(yourHook)