├── .gitignore ├── .vscode ├── launch.json └── tasks.json ├── LICENSE ├── README.md └── src ├── ConsoleApp ├── ConsoleApp.csproj └── Program.cs └── CoreProxy ├── CoreProxy.csproj ├── DispatchProxyDelegate.cs ├── IInterceptor.cs └── ProxyGenerator.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // 使用 IntelliSense 了解相关属性。 3 | // 悬停以查看现有属性的描述。 4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/src/ConsoleApp/bin/Debug/netcoreapp2.1/ConsoleApp.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}/src/ConsoleApp", 15 | "console": "internalConsole", 16 | "stopAtEntry": false, 17 | "internalConsoleOptions": "openOnSessionStart" 18 | }, 19 | { 20 | "name": ".NET Core Attach", 21 | "type": "coreclr", 22 | "request": "attach", 23 | "processId": "${command:pickProcess}" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/src/ConsoleApp/ConsoleApp.csproj" 11 | ], 12 | "problemMatcher": "$msCompile" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 James Yeung 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CoreProxy 2 | 3 | Implement a simple Aop using `System.Reflection.DispatchProxy` 4 | 5 | ### Usage 6 | 7 | ```cs 8 | class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | var poxy1 = (targetInterface)ProxyGenerator.Create(typeof(targetInterface), new SampleProxy("coreproxy1")); 13 | poxy1.Write("here was invoked"); //---> "here was invoked by coreproxy1" 14 | 15 | var poxy2 = (targetInterface)ProxyGenerator.Create(typeof(targetInterface), typeof(SampleProxy), "coreproxy2"); 16 | poxy2.Write("here was invoked"); //---> "here was invoked by coreproxy2" 17 | 18 | var poxy3 = ProxyGenerator.Create("coreproxy3"); 19 | poxy3.Write("here was invoked"); //---> "here was invoked by coreproxy3" 20 | } 21 | } 22 | 23 | 24 | public class SampleProxy : IInterceptor 25 | { 26 | private string proxyName { get; } 27 | 28 | public SampleProxy(string name) 29 | { 30 | this.proxyName = name; 31 | } 32 | 33 | public object Intercept(MethodInfo method, object[] parameters) 34 | { 35 | Console.WriteLine(parameters[0] + " by " + proxyName); 36 | return null; 37 | } 38 | } 39 | 40 | public interface targetInterface 41 | { 42 | void Write(string writesome); 43 | } 44 | ``` -------------------------------------------------------------------------------- /src/ConsoleApp/ConsoleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/ConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using CoreProxy; 4 | 5 | namespace ConsoleApp 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | var poxy1 = (targetInterface)ProxyGenerator.Create(typeof(targetInterface), new SampleProxy("coreproxy1")); 12 | poxy1.Write("here was invoked"); //---> "here was invoked by coreproxy1" 13 | 14 | var poxy2 = (targetInterface)ProxyGenerator.Create(typeof(targetInterface), typeof(SampleProxy), "coreproxy2"); 15 | poxy2.Write("here was invoked"); //---> "here was invoked by coreproxy2" 16 | 17 | var poxy3 = ProxyGenerator.Create("coreproxy3"); 18 | poxy3.Write("here was invoked"); //---> "here was invoked by coreproxy3" 19 | 20 | var poxy4 = ProxyGenerator.Create(new SampleProxy("coreproxy4")); 21 | poxy4.Write("here was invoked"); //---> "here was invoked by coreproxy4" 22 | } 23 | } 24 | 25 | 26 | public class SampleProxy : IInterceptor 27 | { 28 | private string proxyName { get; } 29 | 30 | public SampleProxy(string name) 31 | { 32 | this.proxyName = name; 33 | } 34 | 35 | public object Intercept(MethodInfo method, object[] parameters) 36 | { 37 | Console.WriteLine(parameters[0] + " by " + proxyName); 38 | return null; 39 | } 40 | } 41 | 42 | public interface targetInterface 43 | { 44 | void Write(string writesome); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/CoreProxy/CoreProxy.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/CoreProxy/DispatchProxyDelegate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using System.Reflection; 4 | 5 | 6 | namespace CoreProxy 7 | { 8 | public class DispatchProxyDelegate 9 | { 10 | 11 | private static Func dispatchProxyfunc; 12 | 13 | public static Func GetFunc() 14 | { 15 | if (dispatchProxyfunc == null) 16 | { 17 | var targetType = typeof(TTarget); 18 | var interceptorType = typeof(IInterceptor); 19 | //声明一个返回值变量 20 | var variable = Expression.Variable(targetType); 21 | var parm = Expression.Parameter(interceptorType); 22 | var callexp = Expression.Call(typeof(DispatchProxy), nameof(DispatchProxy.Create), new[] { targetType, typeof(ProxyGenerator) }); 23 | var interceptorProperty = Expression.Property(Expression.Convert(variable, typeof(ProxyGenerator)), "interceptor"); 24 | 25 | var assign1 = Expression.Assign(variable, callexp);//赋值操作 26 | var assign2 = Expression.Assign(interceptorProperty, parm);//给接口赋值 27 | 28 | //构造代码块 29 | var block = Expression.Block(new[] { variable }, parm, assign1, assign2, variable); 30 | dispatchProxyfunc = Expression.Lambda>(block, parm).Compile(); 31 | } 32 | return dispatchProxyfunc; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CoreProxy/IInterceptor.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace CoreProxy 4 | { 5 | public interface IInterceptor 6 | { 7 | object Intercept(MethodInfo method, object[] parameters); 8 | } 9 | } -------------------------------------------------------------------------------- /src/CoreProxy/ProxyGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | 6 | namespace CoreProxy 7 | { 8 | public class ProxyGenerator : DispatchProxy 9 | { 10 | private IInterceptor interceptor { get; set; } 11 | 12 | /// 13 | /// 创建代理实例 14 | /// 15 | /// 所要代理的接口类型 16 | /// 拦截器 17 | /// 代理实例 18 | public static object Create(Type targetType, IInterceptor interceptor) 19 | { 20 | var interceptorType = interceptor.GetType(); 21 | //声明一个返回值变量 22 | var variable = Expression.Variable(targetType); 23 | var callexp = Expression.Call(typeof(DispatchProxy), nameof(DispatchProxy.Create), new[] { targetType, typeof(ProxyGenerator) }); 24 | var interceptorProperty = Expression.Property(Expression.Convert(variable, typeof(ProxyGenerator)), nameof(interceptor)); 25 | var assign1 = Expression.Assign(variable, callexp);//赋值操作 26 | var assign2 = Expression.Assign(interceptorProperty, Expression.Constant(interceptor));//给接口赋值 27 | 28 | //构造代码块 29 | var block = Expression.Block(new[] { variable }, assign1, assign2, variable); 30 | return Expression.Lambda>(block).Compile()();//建议缓存 31 | } 32 | 33 | /// 34 | /// 创建代理实例 35 | /// 36 | /// 所要代理的接口类型 37 | /// 拦截器类型 38 | /// 拦截器构造函数参数值 39 | /// 代理实例 40 | public static object Create(Type targetType, Type interceptorType, params object[] parameters) 41 | { 42 | //声明一个返回值变量 43 | var variable = Expression.Variable(targetType); 44 | 45 | var callexp = Expression.Call(typeof(DispatchProxy), nameof(DispatchProxy.Create), new[] { targetType, typeof(ProxyGenerator) }); 46 | var ctorParams = parameters.Select(x => x.GetType()).ToArray(); 47 | var paramsExp = parameters.Select(x => Expression.Constant(x)); 48 | var newExp = Expression.New(interceptorType.GetConstructor(ctorParams), paramsExp); 49 | var interceptorProperty = Expression.Property(Expression.Convert(variable, typeof(ProxyGenerator)), nameof(interceptor)); 50 | 51 | var assign1 = Expression.Assign(variable, callexp);//赋值操作 52 | var assign2 = Expression.Assign(interceptorProperty, newExp);//给接口赋值 53 | 54 | //构造代码块 55 | var block = Expression.Block(new[] { variable }, assign1, assign2, variable); 56 | return Expression.Lambda>(block).Compile()();//建议缓存 57 | } 58 | 59 | 60 | /// 61 | /// 创建代理实例 TTarget:所要代理的接口类型 TInterceptor:拦截器类型 62 | /// 63 | /// 拦截器构造函数参数值 64 | /// 代理实例 65 | public static TTarget Create(params object[] parameters) where TInterceptor : IInterceptor 66 | { 67 | var targetType = typeof(TTarget); 68 | var interceptorType = typeof(TInterceptor); 69 | //声明一个返回值变量 70 | var variable = Expression.Variable(targetType); 71 | 72 | var callexp = Expression.Call(typeof(DispatchProxy), nameof(DispatchProxy.Create), new[] { targetType, typeof(ProxyGenerator) }); 73 | var ctorParams = parameters.Select(x => x.GetType()).ToArray(); 74 | var paramsExp = parameters.Select(x => Expression.Constant(x)); 75 | var newExp = Expression.New(interceptorType.GetConstructor(ctorParams), paramsExp); 76 | var interceptorProperty = Expression.Property(Expression.Convert(variable, typeof(ProxyGenerator)), nameof(interceptor)); 77 | 78 | var assign1 = Expression.Assign(variable, callexp);//赋值操作 79 | var assign2 = Expression.Assign(interceptorProperty, newExp);//给接口赋值 80 | 81 | //构造代码块 82 | var block = Expression.Block(new[] { variable }, assign1, assign2, variable); 83 | return Expression.Lambda>(block).Compile()();//建议缓存 84 | } 85 | 86 | /// 87 | /// 创建代理实例 TTarget:所要代理的接口类型 TInterceptor:拦截器类型 88 | /// 89 | /// IInterceptor接口 90 | /// 代理实例 91 | public static TTarget Create(IInterceptor iinterceptor) 92 | { 93 | return DispatchProxyDelegate.GetFunc()(iinterceptor); 94 | } 95 | 96 | protected override object Invoke(MethodInfo targetMethod, object[] args) 97 | { 98 | return this.interceptor.Intercept(targetMethod, args); 99 | } 100 | } 101 | } 102 | --------------------------------------------------------------------------------