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 ...
随机推荐
- Python题目练习(二)
1.如何实现对python列表去重,并保持原来顺序 li = [1,2,5,3,1,6,3,8,0,3,2,4] l = [] for i in li: if i not in l: l.append ...
- js隐藏元素
js隐藏元素 $("#serviceType").css('display','none'); js显示元素 $("#serviceType3").css('d ...
- .net core cookie登录和session的 DataProtectionProvider 加入 redis
string redisConnectionString = Configuration.GetSection("Storage:Redis").GetValue<strin ...
- exporter API(导出、输出器api)moodel3.3
Moodle[导出器]是接收数据并将其序列化为一个简单的预定义结构的类.它们确保输出的数据格式统一,易于维护.它们也用于生成外部函数的签名(参数和返回值) 外部函数定义在moodle/lib/exte ...
- 数据结构--图 的JAVA实现(上)
1,摘要: 本系列文章主要学习如何使用JAVA语言以邻接表的方式实现了数据结构---图(Graph),这是第一篇文章,学习如何用JAVA来表示图的顶点.从数据的表示方法来说,有二种表示图的方式:一种是 ...
- ReentrantLock和condition源码浅析(一)
转载请注明出处..... 一.介绍 大家都知道,在java中如果要对一段代码做线程安全操作,都用到了锁,当然锁的实现很多,用的比较多的是sysnchronize和reentrantLock,前者是ja ...
- hadoop安装过程中出现的错误
此次来记录一下我在安装Hadoop安装过程中出现的错误,安装过程参照慕课网林子雨教程进行安装,在尝试过程中出现的错误如下: 1.在安装Ubuntu时,新建虚拟电脑时,并没有在版本的输入框中有Ubunt ...
- HOJ3237----BFS/DFS
/* 注意两点 . 不可以使用替换可用节点为不可用节点的方法进行DFS 因为角落也可能有油,替换了就出不来.(某学长指导) . 可用通过开一个数组(例如我的b[][]数组) 用了存储到当前位置剩余最大 ...
- 2017-9-10-Vim使用说明
首先,很多linux发行版直接进入的是vi,不是vim,刚开始使用vi会有点蒙,需要改一下配置文件到vim:"打开vi编辑器,输入i,左下角没有出现-INSERT-字样,且编辑模式跟vim不 ...
- go学习资源
教程 GO 命令教程 Go示例学 Book <Go Web 编程> <Go入门指南> <深入解析Go> 应该是go的进阶,等熟悉go之后再来看 <Go语言圣经 ...