C#靜態(tài)代碼織入AOP組件之Rougamo的使用詳解
寫在前面
關(guān)于肉夾饃組件的官方介紹說明:
Rougamo是一個(gè)靜態(tài)代碼織入的AOP組件,同為AOP組件較為常用的有Castle、Autofac、AspectCore等,與這些組件不同的是,這些組件基本都是通過動態(tài)代理+IoC的方式實(shí)現(xiàn)AOP,是運(yùn)行時(shí)完成的,而Rougamo是編譯時(shí)直接修改目標(biāo)方法織入IL代碼的。如果你還知道一個(gè)AOP組件"PostSharp",那么Rougamo就是類似Postsharp的一個(gè)組件,Postsharp是一個(gè)成熟穩(wěn)定的靜態(tài)代碼織入組件,但PostSharp是一款商業(yè)軟件,一些常用的功能在免費(fèi)版本中并不提供。
老規(guī)矩從NuGet 安裝組件 Rougamo.Fody
代碼實(shí)現(xiàn)
以下是最基礎(chǔ)的一個(gè)應(yīng)用肉夾饃AOP組件的實(shí)現(xiàn)代碼
注入代碼主體[LoggingAttribute]:
public class LoggingAttribute : MoAttribute { private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); public override void OnEntry(MethodContext context) { // 從context對象中能取到包括入?yún)?、類?shí)例、方法描述等信息 Logger.Info("方法執(zhí)行前"); } public override void OnException(MethodContext context) { Logger.Error("方法執(zhí)行異常", context.Exception); } public override void OnSuccess(MethodContext context) { Logger.Info("方法執(zhí)行成功后"); } public override void OnExit(MethodContext context) { Logger.Info("方法退出時(shí),不論方法執(zhí)行成功還是異常,都會執(zhí)行"); } } // 3.應(yīng)用Attribute public class Service { [Logging] public static int Sync(Model model) { return model.Id; } [Logging] public async Task<Data> Async(int id) { return await Task.Run(() => { var data = new Data(); data.Id = id; return data; }); } } public class Model { public int Id { get; set; } public string Name { get; set; } } public class Data { public int Id { get; set; } }
調(diào)用代碼:
public static void Main(string[] args) { Console.WriteLine("Start..."); var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; var service = new Service(); var data = service.Async(1); var id = Service.Sync(new Model() { Id = 1, Name = "DemoModel" }); Console.WriteLine($"Data Id: {data.Id}, Model Id: {id}"); Console.ReadLine(); }
調(diào)用示例
到此這篇關(guān)于C#靜態(tài)代碼織入AOP組件之Rougamo的使用詳解的文章就介紹到這了,更多相關(guān)C#靜態(tài)代碼織入AOP組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用設(shè)計(jì)模式中的工廠方法模式進(jìn)行C#編程的示例講解
這篇文章主要介紹了使用設(shè)計(jì)模式中的工廠方法模式進(jìn)行C#編程的示例講解,工廠方法模式可以看作是對簡單工廠模式的進(jìn)一步擴(kuò)展,需要的朋友可以參考下2016-02-02Unity 2017使用UGUI實(shí)現(xiàn)大轉(zhuǎn)盤抽獎
這篇文章主要為大家詳細(xì)介紹了Unity 2017使用UGUI實(shí)現(xiàn)大轉(zhuǎn)盤抽獎,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02