.Net AOP (四)EnterpriseLibary 實現方法
首先添加EnterpriseLibary的引用
自定義CallHandler,這裏定義兩個CallHandler分別用於參數檢查和日誌記錄。
using Microsoft.Practices.Unity.InterceptionExtension;
public class UserHandler:ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
User user = input.Inputs[0] as User;
if (user.PassWord.Length < 10)
{
return input.CreateExceptionMethodReturn(new UserException("密碼長度不能小於10位"));
}
Console.WriteLine("參數檢測無誤");
return getNext()(input, getNext);
}
}
public class LogHandler:ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
User user = input.Inputs[0] as User;
Log log = new Log() { Message = string.Format("RegUser:Username:{0},Password:{1}", user.Name, user.PassWord), Ctime = DateTime.Now };
Console.WriteLine("日誌已記錄,Message:{0},Ctime:{1}",log.Message,log.Ctime);
var messagereturn = getNext()(input, getNext);
return messagereturn;
}
}
定義對應的HandlerAttribute
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.Unity;
public class UserHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
ICallHandler handler = new UserHandler(){Order=this.Order};
return handler;
}
}
public class LogHandlerAttribute:HandlerAttribute
{
public int Order { get; set; }
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new LogHandler() { Order = this.Order };
}
}
用戶註冊接口和實現,這裏通過爲接口添加attribute的方式實現。order值表示執行順序,值小的先執行。
[LogHandlerAttribute(Order=2)]
[UserHandlerAttribute(Order=1)]
public interface IUserProcessor
{
void RegUser(User user);
}
public class UserProcessor : MarshalByRefObject,IUserProcessor
{
public void RegUser(User user)
{
Console.WriteLine("用戶已註冊。");
}
}
測試
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
public class Client
{
public static void Run()
{
try
{
User user = new User() { Name = "lee", PassWord = "123123123123" };
UserProcessor userprocessor = PolicyInjection.Create<UserProcessor>();
userprocessor.RegUser(user);
}
catch(Exception ex)
{
throw ex;
}
}
}