C#靜態(tài)代碼織入AOP組件之Rougamo的使用詳解
寫在前面
關于肉夾饃組件的官方介紹說明:
Rougamo是一個靜態(tài)代碼織入的AOP組件,同為AOP組件較為常用的有Castle、Autofac、AspectCore等,與這些組件不同的是,這些組件基本都是通過動態(tài)代理+IoC的方式實現(xiàn)AOP,是運行時完成的,而Rougamo是編譯時直接修改目標方法織入IL代碼的。如果你還知道一個AOP組件"PostSharp",那么Rougamo就是類似Postsharp的一個組件,Postsharp是一個成熟穩(wěn)定的靜態(tài)代碼織入組件,但PostSharp是一款商業(yè)軟件,一些常用的功能在免費版本中并不提供。
老規(guī)矩從NuGet 安裝組件 Rougamo.Fody

代碼實現(xiàn)
以下是最基礎的一個應用肉夾饃AOP組件的實現(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)ⅰ㈩悓嵗?、方法描述等信?
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("方法退出時,不論方法執(zhí)行成功還是異常,都會執(zhí)行");
}
}
// 3.應用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)用示例


到此這篇關于C#靜態(tài)代碼織入AOP組件之Rougamo的使用詳解的文章就介紹到這了,更多相關C#靜態(tài)代碼織入AOP組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Unity 2017使用UGUI實現(xiàn)大轉(zhuǎn)盤抽獎
這篇文章主要為大家詳細介紹了Unity 2017使用UGUI實現(xiàn)大轉(zhuǎn)盤抽獎,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02

