AOP - C# Fody中的方法和属性拦截
很久很久以前用过postsharp来做AOP, 大家知道的,现在那东东需要付费,于是尝试了一下Fody,但是发现Fody跟新太快了,所以大家在安装fody的时候尽力安装老的版本:packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Cauldron.Interception.Fody" version="2.0.27" targetFramework="net461" />
<package id="Costura.Fody" version="1.6.2" targetFramework="net461" developmentDependency="true" />
<package id="Fody" version="2.5.0" targetFramework="net461" developmentDependency="true" />
</packages>
创建一个方法拦截的demo如下:
using Cauldron.Interception;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace FodyTest
{ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class LoggerAttribute : Attribute, IMethodInterceptor
{
private string methodName; public void OnEnter(Type declaringType, object instance, MethodBase methodbase, object[] values)
{
this.methodName = methodbase.Name;
this.AppendToFile($"Enter -> {declaringType.Name} {methodbase.Name} {string.Join(" ", values)}");
} public void OnException(Exception e) => this.AppendToFile($"Exception -> {e.Message}"); public void OnExit() => this.AppendToFile($"Exit -> {this.methodName}"); private void AppendToFile(string line)
{
File.AppendAllLines("log.txt", new string[] { line });
Console.WriteLine(">> " + line);
}
}
}
属性拦截如下:
using Cauldron.Interception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FodyTest
{ [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class OnPropertySetAttribute : Attribute, IPropertySetterInterceptor
{
[AssignMethod("{CtorArgument:0}")]
public Action<string, object> onSetMethod = null; public OnPropertySetAttribute(string methodName)
{
} public void OnException(Exception e)
{
} public void OnExit()
{
} public bool OnSet(PropertyInterceptionInfo propertyInterceptionInfo, object oldValue, object newValue)
{
this.onSetMethod?.Invoke(propertyInterceptionInfo.PropertyName, newValue);
return false;
}
}
}
创建FodyWeavers.xml:
<?xml version="1.0" encoding="utf-8"?>
<Weavers>
<Cauldron.Interception />
<Costura />
</Weavers>
调用code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FodyTest
{
[OnPropertySet(nameof(ExecuteMe))]
public class PropertySetterTestClass
{
public int BookId { get; set; }
public string BookName { get; set; } private void ExecuteMe(string propertyName, object newValue) =>
Console.WriteLine($"The property '{propertyName}' has a new value: '{newValue ?? ""}'");
} [Logger]
internal class Program
{
private static int Add(int a, int b) => a + b; private static void Main(string[] args)
{
Console.WriteLine(Add(, )); var sampleClass = new PropertySetterTestClass
{
BookName = "50 shades of C#",
BookId =
}; Console.ReadLine();
}
}
}
运行效果:

AOP - C# Fody中的方法和属性拦截的更多相关文章
- JavaScript中的方法和属性
书读百遍其义自见 学习<JavaScript设计模式>一书时,前两个章节中的讲解的JavaScript基础知识,让我对属性和方法有了清晰的认识.如下是我的心得体会以及部分摘录的代码. 不同 ...
- (转)C# Aop简单扫盲及ORM实体类属性拦截示例
转自: http://www.cnblogs.com/cyq1162/archive/2012/05/30/2526573.html 先说下场景,C#中为什么要使用Aop,而我又是在哪里使用Aop? ...
- Postsharp基本用法——方法、属性拦截与异常处理
以下Demo代码基于 .NET Core 演示了Postsharp的基本使用方法,稍作修改(反射部分有些许差异)也适用于.NET Framework. 更多高级使用方法详见官方文档.http://sa ...
- python-day33--Process类中的方法及属性
p.daemon = True -->守护进程,守护进程不可以再有子进程,并且主进程死守护进程就死,要写在p.start()之前 p.join() ---> 主进程等子进程执行完 之后再结 ...
- django定义Model中的方法和属性
#定义一个Model class UserProfile(models.Model): user=models.OneToOneField(User,unique=True) phone=models ...
- Spring之AOP在XML中的配置方法
AOP 即 Aspect Oriental Program 面向切面编程 先来一个栗子: <aop:config> <aop:pointcut id="loggerCutp ...
- 全面理解Javascript中Function对象的属性和方法
http://www.cnblogs.com/liontone/p/3970420.html 函数是 JavaScript 中的基本数据类型,在函数这个对象上定义了一些属性和方法,下面我们逐一来介绍这 ...
- Asp.net mvc 中Action 方法的执行(一)
[toc] 在 Aps.net mvc 应用中对请求的处理最终都是转换为对某个 Controller 中的某个 Action 方法的调用,因此,要对一个请求进行处理,第一步,需要根据请求解析出对应的 ...
- window对象的方法和属性汇总
window对象有以下方法: open close alert confirm prompt setTimeout clearTimeout setInterval clearInterval mov ...
随机推荐
- Codeforces 513E2 Subarray Cuts dp (看题解)
我们肯定要一大一小间隔开来所以 把式子拆出来就是类似这样的形式 s1 - 2 * s2 + 2 * s3 + ...... + sn 然后把状态开成四个, 分别表示在顶部, 在底部, 在顶部到底部的中 ...
- 系统环境变量(就是不需要切换目录,敲击“python”就可以进入编码器)
1.右击我的电脑,选择属性,选择“高级系统设置” 2.选择高级,选择环境变量 3.在系统变量中找到path,点击编辑.然后新建,将python的路径复制进去,点击确定.
- AtCoder Grand Contest 002 (AGC002) F - Leftmost Ball 动态规划 排列组合
原文链接https://www.cnblogs.com/zhouzhendong/p/AGC002F.html 题目传送门 - AGC002F 题意 给定 $n,k$ ,表示有 $n\times k$ ...
- Vue 中 computed、watch对比
computed:就像调用VUE的DATA一样 watch的对比 :监听事件
- JavaEE 之 log4j
1.log4j a.概念:一个非常优秀的开源日志记录工具 b.配置: ①src同目录下建立log4j.properties文件,书写: log4j.rootLogger=debug,appender1 ...
- ASP.NET Core的Data Protect(数据保护)的学习和应用
转载请注入出处: https://home.cnblogs.com/u/zhiyong-ITNote/ dotnet core中提供了一个新的身份验证框架Identity,它不同于dot net下的身 ...
- SQL 自定义存储过程报错
begin catch ), @ErrSeverity int SELECT @ErrMsg = ' SP Error: '+ERROR_MESSAGE(), @ErrSeverity = ERROR ...
- 9. Fizz Buzz 问题
Description Given number n. Print number from 1 to n. But: when number is divided by 3, print " ...
- python基础一 ------可迭代类型的连接
对可迭代迭代进行连接,返回一个可迭代对象 两种方式: 并行连接 zip() 串行连接 itertools.chain from itertools import chain #并行连接 print(& ...
- window下安装PIL
PIL非官方库64 友情连接: https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ ...