好的,所以这里...
首先假设我们有这个域类定义:
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。
如果你绝对必须绕过 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();