Friday, January 18, 2013

Unity , Aspect Oriented and Interceptor for C#

Example using MVC 4 , Unity, AOP , Interceptor
 













 
In C#
 
 public class Interceptor : IInterceptionBehavior
    {
        /// 
        /// Returns the interfaces required by the behavior for the objects it intercepts.
        /// 
        /// 
        /// The required interfaces.
        /// 
        public IEnumerable GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        /// 
        /// Implement this method to execute your behavior processing.
        /// 
        /// Inputs to the current call to the target.
        /// Delegate to execute to get the next delegate 
        /// in the behavior chain
        /// 
        /// Return value from the target.
        /// 
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            /* Call the method that was intercepted */
            string className = input.MethodBase.DeclaringType.Name;
            string methodName = input.MethodBase.Name;
            string generic = input.MethodBase.DeclaringType.IsGenericType ? string.Format("<{0}>", input.MethodBase.DeclaringType.GetGenericArguments().ToStringList()) : string.Empty;
            string arguments = input.Arguments.ToStringList();
            string preMethodMessage = string.Format("{0}{1}.{2}({3})", className, generic, methodName, arguments);


            var auditLog = new AuditLog();
            auditLog.UserName = Environment.UserName;
            auditLog.ActivityType = string.Format("ClassName - {0} : MethodName - {1}", className, methodName);
            auditLog.Description = preMethodMessage;


            Task.Factory.StartNew(() => Logger.Instance.Log(auditLog));
            
            
            IMethodReturn msg = getNext()(input, getNext);            
            string postMethodMessage = string.Format("{0}{1}.{2}() -> {3}", className, generic, methodName, msg.ReturnValue);
            auditLog.Description = postMethodMessage;
            Task.Factory.StartNew(() => Logger.Instance.Log(auditLog));            
            return msg;
        }

        public bool WillExecute
        {
            get { return true; }
        }
    }

 

No comments: