postsharp初体验
首先,有必要先介紹下,什么叫做AOP(Aspect-Oriented Programming,面向切面編程)。下圖是百度的詞條解釋
用圖來解釋可能更直接了當些:
ps:圖片來自http://www.cnblogs.com/leoo2sk/archive/2010/11/30/aop-postsharp.html
簡單的說,AOP是一種獨立于系統業務邏輯的貫穿整個系統的橫切關注點,比如異常處理,日志的記錄等。
--------------------------------------------------------------------------------------------------------------------------
之前在項目中,經常碰到的問題是:如何給所有的方法都加上一個統一的異常處理的方法,特別是cs模式的(bs模式比較簡單,可以通過在Global文件中捕獲異常,并記錄)。另外之前面試時,也被問到類似的問題,當時我思考了很長時間,還是想不出什么好的辦法。后來今天看MVC4 web編程一書時,文中提到可以通過特性來統一記錄異常日志。于是,我欣喜若狂,趕緊百度相關的技術的文章,發現了一個非常好用的AOP的插件,也就是這篇文章的主角:PostSharp
1. 下載PostSharp(https://www.postsharp.net/)。現在版本已經更新到4.1。1.5是免費的,大于2.0的版本都是收費的。我下了個3.0的版本及其keygen。有需要的加我q(371323761)
2. 安裝PostSharp。過程很簡單,按照其流程即可。按照后,打開keygen,生成License即可。
3. 打開vs,右鍵項目,選擇Add PostSharp to project,如下圖,接下來便可以用PostSharp來寫些AOP的應用了
----------------------------------------------------------------------------------------------------------------
比如我們想對每個類的每個方法做異常日志記錄
1. 定義日志記錄類
namespace CustomAttribute {public interface ILog{void log(string msg);} } [Serializable]public class Logger:ILog{public void log(string msg){string path = Environment.CurrentDirectory + "\\" + string.Format("systemlog/{0}/{1}/{2}", "error", DateTime.Now.Year, DateTime.Now.Month);if (!Directory.Exists(path)){Directory.CreateDirectory(path);}string logPath = path + "/" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt";if (!File.Exists(logPath)){var file = File.Create(logPath);file.Close();}StreamWriter sw = new StreamWriter(logPath, true);sw.WriteLine(msg);sw.Flush();sw.Close();}}2. 定義異常日志記錄的特性
[Serializable][AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]public class ExceptionLogAttribute : OnMethodBoundaryAspect{private ILog logger;//通過依賴注入的方式解耦public ExceptionLogAttribute(ILog log){logger = log;}public override void OnException(MethodExecutionArgs args){base.OnException(args);logger.log(string.Format("{0}:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), args.Exception.Message));}} [Serializable][AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]//AttributeTargets.Method說明該特性是應用到方法上的 public sealed class MyExceptionLogAttribute:ExceptionLogAttribute { public MyExceptionLogAttribute() : base(new Logger()) { } }3. 應用特性到方法上
class Program{static void Main(string[] args){Console.WriteLine(Divide(1, 0));Console.ReadLine();}[MyExceptionLog]private static int Divide(int a, int b){return a / b;}}4. 結果
PostSharp還有很多用處,日后再慢慢挖掘。
很喜歡PostSharp官網上的一句話:
Start writing cleaner code?today!
以前寫代碼總是關注于如何實現功能,后來慢慢學會用設計模式重構代碼,現在懂得了AOP(postsharp),便可以從另外一個角度,以更優雅的方式寫代碼。
?------------------------
問題1:如果想對類的所有方法定義統一的異常日志記錄的特性,怎么辦呢?
如果把特性Targets定義為All或class,可以捕獲該類的所有的方法的異常
問題2:如果想對程序集(dll)中每個方法定義異常日志記錄的特性,怎么呢?
把特性的Targets定義為all或Assembly,然后在AssemblyInfo.cs文件中,新增程序集的特性
轉載于:https://www.cnblogs.com/xingluzhe/p/4738150.html
總結
以上是生活随笔為你收集整理的postsharp初体验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: stagefright omx小结
- 下一篇: 关于重写session实现的时候可能会导