Base class interceptor

Jan 21, 2011 at 12:43 PM

I would like to set up an interceptor for a base class.

I have a layer supertype from which all other business objects derive and I want to use Interception to provide me with a way of using attributes to make all derived objects e.g. log or notify changes etc.

class BaseClass

class SomeObject: BaseClass

I would like to be able to do this:

.SetDefaultInterceptorFor<BaseClass)(new TranparentProxyInterceptor());

So far all this works if I supply "SomeObject" into the SetDefaultInterceptorFor type parameter, but I don't want to have to do that for ALL my derived objects (there could be hundreds.) When I supply "BaseClass" as above then the interception does not work.

Is this possible?


Jan 26, 2011 at 4:34 AM

The interception, and actually all Unity configuration, has to be on the concrete type that's being registered. The container doesn't go looking up inheritance hierarchies looking for configuration on base classes; there's too many corner cases and performance pitfalls to want to put that into the container.

Having said that, in a similar situation what I did was write a small bit of code via the reflection API to walk through loaded assemblies, and look for the types in those assemblies. When I find one matching the criteria (derived from the base class, in your case) then call the container API to set up interception. It's only about 6-10 lines of code, and you don't need to do anything else, when you add a new type to the system it'll get picked up automatically.


Jan 26, 2011 at 1:34 PM

Ok, I think I understand your suggestion.

Instead of loading the Unity Container with the three lines of code above, I should load the assembly and iterate through all the loaded types and see if they are subclasses of my base class. If they are I should then add each one to the Unity container.
Thanks for your idea, I think it will work well.