好了,所以这里去...
首先假设我们有这个领域类的定义:
public interface IInterceptableClass
{
string FirstName { get; set; }
string LastName { get; }
string GetLastName();
}
public class InterceptableClass : IInterceptableClass
{
public string FirstName { get; set; }
public string LastName { get; private set; }
public InterceptableClass()
{
LastName = "lastname";
}
public string GetLastName()
{
return LastName;
}
}
并假设你有一个像这样定义一个简单的拦截行为:
internal class SampleInterceptorBehavior : IInterceptionBehavior
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
// this invokes the method at the tip of the method chain
var result = getNext()(input, getNext);
// method executed with no exceptions (yay)
if (result.Exception == null)
{
//input.Target
Console.WriteLine($"intercepting: target={input.Target.ToString()}, method={input.MethodBase.Name}");
}
else // boo..!
{
// handle exception here
Console.WriteLine($"error! message={result.Exception?.Message}");
}
return result;
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public bool WillExecute { get { return true; } }
}
你可以通过Unity
这样连接:
static void Main(string[] args)
{
var container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<IInterceptableClass, InterceptableClass>(
new Interceptor<TransparentProxyInterceptor>(),
new InterceptionBehavior<SampleInterceptorBehavior>());
var myInstance = container.Resolve<IInterceptableClass>();
// just want to illustrate that privae sets are not supported...
myInstance.FirstName = "firstname";
var lastname = myInstance.GetLastName();
Console.ReadLine();
}
请注意,如果您不使用而不是使用Unity来连接拦截,则您必须手动执行此操作。对于一次性,一些开发者可能会更喜欢这种方式,但在实践中,我总是发现这条路是不可持续的,并且有多个截取点,非常残酷。所以如果可以的话,总是使用Unity。
如果你绝对必须的,虽然绕过团结,这里是你如何做到这一点:
var manualInstance = Intercept.ThroughProxy<IInterceptableClass>(
new InterceptableClass(), // <-- this could be an already-existing instance as well...
new TransparentProxyInterceptor(),
new IInterceptionBehavior[]
{
new SampleInterceptorBehavior()
});
manualInstance.FirstName = "firstname";
var lastname = manualInstance.GetLastName();
这是完全可行的 - 一旦我在办公室落户,将发布一些代码给你。 – code4life
谢谢,这将是非常好的:)! – Inx51