我正在尝试使用Castle DynamicProxy,但是受this one等教程启发的最基本的代码失败了。
为了简化操作,我将所有代码放在一个文件中,因此它足够短,可以在这里复制粘贴:
namespace UnitTests
{
using Castle.DynamicProxy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
[TestClass]
public class DemoTests
{
[TestMethod]
public void TestHelloMethodThroughProxy()
{
var proxy = new ProxyGenerator().CreateClassProxy<Demo>(new DemoInterceptor());
var actual = proxy.SayHello();
var expected = "Something other";
Assert.AreEqual(expected, actual);
}
}
[Serializable]
public class DemoInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.ReturnValue = "Something other";
}
}
public class Demo
{
public string SayHello()
{
return "Hello, World!";
}
}
}
代码由一个单元测试组成,它生成一个类的代理,然后通过代理调用该类的方法。
代理旨在通过简单地分配结果值来绕过对原始方法的调用,而无需调用原始方法。
如果我将invocation.ReturnValue = "Something other";
替换为throw new NotImplementedException();
,则测试结果仍然完全相同,并且不会抛出异常,表示可能未调用代码。在调试模式下,也未达到Intercept
方法中的断点。
为了调用拦截器,我需要做什么?
答案 0 :(得分:1)
Castle Windsor只能截取界面或虚拟成员。您的$SAMs = Get-ADUser -filter * -Properties ProfilePath | ? {$_.ProfilePath -eq $Null} | Select SamaccountName
foreach ($SAM in $SAMs)
{
$NewDir = New-Item $SAM -Type Directory -Path "ChooseYourPath" ## Create the Folder in desired path
Set-ADUser $SAM -ProfilePath $NewDir.FullName ## Set the AD User Account ProfilePath Property with the New Folder
}
方法未标记为虚拟,因此未被截获。
将方法标记为虚拟或使用接口。
参考Why can Windsor only intercept virtual or interfaced methods?