|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionMany times, we need to intercept method calls, and enable some code to run before/after a method call of an external type (.NET object). This article shows how to intercept the methods of an external type, generating method proxies by using injection of IL code. The dynamic type factoryThis factory will generate the dynamic types and return them to the caller. This emulates the external type, and intercepts the specified methods added in the interface. The factory needs the external type and an interface, which establishes the methods that will be intercepted. The sample code here below creates the new type: public static object Create(object externalTarget, Type interfaceType)
{
Type proxyType= EmiProxyType(target.GetType(),interfaceType);
return Activator.CreateInstance(proxyType ,
new object[]{externalTarget,interfaceType});
}
After providing the factory with the target object ( Defining the interfaceAs previously said, the interface we pass to the factory specifies which methods we want to intercept; moreover, implemented attributes (AOP) will define the desired behavior. public interface IBussinesLogicEmployees
{
[CountingCalls]
[LoggerToFile]
EnterpriseDemo.Employees GetEmployees(
EnterpriseDemo.BussinesLogicEmployees.Delegation delegation);
}
This interface sets the method Defining the attributesThe attributes have tree behaviors inside the method that create the factory:
By default, implement three attributes:
Additionally, I have created a custom attribute, How to intercept an external type method?To intercept an external type method, we must follow these steps:
In our case, looking at the interface method
If, instead, we decorate our interface this way: public interface IBussinesLogicEmployees {
[LoggerToFile]
[LoggerExceptionToFile]
[ExternalFilter]
EnterpriseDemo.Employees GetEmployees(
EnterpriseDemo.BussinesLogicEmployees.Delegation delegation);
}
the factory generated method will create a log file with information about the method call, will create a log file with information about the exception generated by the external type method, will execute the external type method, and finally, will filter the typed dataset returned depending on whether the employees are marked as external or not.
ConclusionIn the .NET platform, Aspect Oriented Programming (AOP) can be achieved mainly on two approaches: injecting the IL with the desired code, or alternatively, inheriting the classes from the .NET CLR Library class History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||