AOP is a programming paradigm that extends OOP (Object-Oriented Programming) (it does not replace OOP but extends it).
Introducing AOP helps to:
Separate core logic from non-core logic code, which reduces module coupling and facilitates future extensions.
Non-core logic code includes aspects like: (logging, performance statistics, security control, transaction processing, exception handling, etc.), separating them from business logic code.
For example:
Instead of embedding logging-related code within business logic methods, which violates the single responsibility principle, we can refactor and extract logging methods (as shown in the right image).
like below image.
Classic Example: In Asp.Net MVC, Controller, Action filters (FilterAttribute)
AwesomeProxy.Net mainly intercepts method processing:
- Before method execution
- After method execution
- On method exception
How to Use: Usage is similar to Controller, Action filters in Asp.Net MV
- Write an attribute to mark the interception action
public class CacheAttribute : AopBaseAttribute
{
public string CacheName { get; set; }
public override void OnExecting(ExecuteingContext context)
{
object cacheObj = CallContext.GetData(CacheName);
if (cacheObj != null)
{
context.Result = cacheObj;
}
}
public override void OnExecuted(ExecutedContext context)
{
CallContext.SetData(CacheName, context.Result);
}
}
- Inherit the class to be intercepted from
MarshalByRefObject
public class CacheService : MarshalByRefObject
{
[Cache]
public string GetCacheDate()
{
return DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
}
}
- Dynamically generate the proxy class using
ProxyFactory.GetProxyInstance
CacheService cache = ProxyFactory.GetProxyInstance<CacheService>();
- Directly call the method to execute the interception action on the attribute
CacheService cache = ProxyFactory.GetProxyInstance<CacheService>();
Console.WriteLine(cache.GetCacheDate());
- Write an attribute to mark the interception action
public class CacheAttribute : AopBaseAttribute
{
public string CacheName { get; set; }
public override void OnExecuted(ExecutedContext context)
{
CallContext.SetData(CacheName, context.Result);
}
public override void OnExecuting(ExecutingContext context)
{
object cacheObj = CallContext.GetData(CacheName);
if (cacheObj != null)
{
context.Result = cacheObj;
}
}
}
- Create an interface and class
public class CacheService : ICacheService
{
public string GetCacheDate()
{
return DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
}
}
public interface ICacheService {
[Cache(CacheName = "GetCacheDate")]
public string GetCacheDate();
}
- Dynamically generate the proxy class using
ProxyFactory.GetProxyInstance
var cache = ProxyFactory.GetProxyInstance<CacheService>();
- Directly call the method to execute the interception action on the attribute
var cache = ProxyFactory.GetProxyInstance<CacheService>();
Console.WriteLine(cache.GetCacheDate());
- Write Log
- Permission Verification
- Caching
Unit Test Results