Search code examples
postsharp

PostSharp intercept class constructor and destructor calls


Is it possible to intercept class constructor and destructor calls using PostSharp? I would like to create active instances counter for classes.


Solution

  • You can use OnMethodBoundaryAspect on constructor and destructors. Note that classes don't have destructors by default in C# and VB, and destructors are called at a non-deterministic moment.

    Remember that constructors can be called in chain, and the aspect is going to be applied on every constructor in the chain.