/// <summary> /// 增加拦截器 /// </summary> /// <param name="proxy">动态代理</param> /// <param name="interceotors">要增加的拦截器</param> private void AddInterceptions(IInterceptingProxy proxy, IList <IInterception> interceotors) { for (var i = 0; i < interceotors.Count; i++) { proxy.AddInterception(interceotors[i]); } }
/// <summary> /// 创建代理类 /// </summary> /// <param name="target">服务实例</param> /// <param name="bindData">服务绑定数据</param> /// <returns>如果构建成功则返回服务透明代理实例,否则返回服务实例</returns> public object Bound(object target, BindData bindData) { if (target == null) { return(null); } var interceptors = bindData.GetInterceptors(); if (interceptors == null) { return(target); } IInterceptingProxy proxy = null; if (target is MarshalByRefObject) { if (target.GetType().IsDefined(typeof(AopAttribute), false)) { proxy = CreateRealProxy(target); } } if (proxy == null) { return(target); } AddInterceptions(proxy, interceptors); return(proxy.GetTransparentProxy()); }
public void ParametersPassProperlyToTarget() { IInstanceInterceptor interceptor = new InterfaceInterceptor(); MyDal target = new MyDal(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IDal), target); CallCountHandler depositHandler = new CallCountHandler(); CallCountHandler withdrawHandler = new CallCountHandler(); proxy.SetPipeline(typeof(IDal).GetMethod("Deposit"), new HandlerPipeline(new ICallHandler[] { depositHandler })); proxy.SetPipeline(typeof(IDal).GetMethod("Withdraw"), new HandlerPipeline(new ICallHandler[] { withdrawHandler })); IDal intercepted = (IDal)proxy; intercepted.Deposit(100.0); intercepted.Deposit(25.95); intercepted.Deposit(19.95); intercepted.Withdraw(15.00); intercepted.Withdraw(6.25); Assert.AreEqual(3, depositHandler.CallCount); Assert.AreEqual(2, withdrawHandler.CallCount); Assert.AreEqual(100.0 + 25.95 + 19.95 - 15.00 - 6.25, target.Balance); }
/// <summary> /// Called during the chain of responsibility for a build operation. The /// PostBuildUp method is called when the chain has finished the PreBuildUp /// phase and executes in reverse order from the PreBuildUp calls. /// </summary> /// <remarks>In this class, PostBuildUp checks to see if the object was proxyable, /// and if it was, wires up the handlers.</remarks> /// <param name="context">Context of the build operation.</param> /// <param name="pre"></param> public override void PostBuildUp(IBuilderContext context) { IInterceptingProxy proxy = context.Existing as IInterceptingProxy; if (proxy == null) { return; } var effectiveInterceptionBehaviorsPolicy = (EffectiveInterceptionBehaviorsPolicy)context.Policies .Get(context.OriginalBuildKey.Type, context.OriginalBuildKey.Name, typeof(EffectiveInterceptionBehaviorsPolicy), out _); if (effectiveInterceptionBehaviorsPolicy == null) { return; } foreach (var interceptionBehavior in effectiveInterceptionBehaviorsPolicy.Behaviors) { proxy.AddInterceptionBehavior(interceptionBehavior); } }
public void ThrowingFromInterceptedMethodStillRunsAllHandlers() { MethodInfo thrower = typeof(ClassWithDefaultCtor).GetMethod("NotImplemented"); ClassWithDefaultCtor instance = WireupHelper.GetInterceptingInstance <ClassWithDefaultCtor>(); IInterceptingProxy pm = (IInterceptingProxy)instance; CallCountHandler handler = new CallCountHandler(); PostCallCountHandler postHandler = new PostCallCountHandler(); HandlerPipeline pipeline = new HandlerPipeline(new ICallHandler[] { postHandler, handler }); PipelineManager manager = new PipelineManager(); manager.SetPipeline(thrower, pipeline); pm.AddInterceptionBehavior(new PolicyInjectionBehavior(manager)); try { instance.NotImplemented(); Assert.Fail("Should have thrown before getting here"); } catch (NotImplementedException) { // We're expecting this one } Assert.AreEqual(1, handler.CallCount); Assert.AreEqual(1, postHandler.CallsCompleted); }
/// <summary> /// 增加拦截器 /// </summary> /// <param name="proxy">代理</param> /// <param name="interceotors">要增加的拦截器</param> /// <returns></returns> private IInterceptingProxy AddInterceptions(IInterceptingProxy proxy, IInterception[] interceotors) { for (int i = 0; i < interceotors.Length; i++) { proxy.AddInterception(interceotors[i]); } return(proxy); }
private void SetPipeline(PipelineManager manager, object instance, string methodName, params ICallHandler[] handlers) { HandlerPipeline pipeline = new HandlerPipeline(handlers); MethodInfo targetMethod = instance.GetType().BaseType.GetMethod(methodName); IInterceptingProxy proxy = (IInterceptingProxy)instance; manager.SetPipeline(targetMethod, pipeline); }
private void ApplyPolicies(IInterceptor interceptor, IInterceptingProxy proxy, object target, PolicySet policies) { foreach (MethodImplementationInfo method in interceptor.GetInterceptableMethods(target.GetType(), target.GetType())) { HandlerPipeline pipeline = new HandlerPipeline(policies.GetHandlersFor(method, container)); proxy.SetPipeline(method.ImplementationMethodInfo, pipeline); } }
public void CanAddInterceptionBehaviorsToPipeline() { ClassWithDefaultCtor instance = WireupHelper.GetInterceptingInstance <ClassWithDefaultCtor>(); IInterceptingProxy pm = (IInterceptingProxy)instance; CallCountInterceptionBehavior interceptor = new CallCountInterceptionBehavior(); pm.AddInterceptionBehavior(interceptor); }
public void AssortedParameterKindsAreProperlyHandled() { var interceptor = new VirtualMethodInterceptor(); var type = interceptor.CreateProxyType(typeof(AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds)); IInterceptingProxy proxy = Activator.CreateInstance(type) as IInterceptingProxy; AssortedParameterKindsAreProperlyHandledHelper.PerformTest(proxy); }
[Ignore] // TODO: Known issue - we don't copy attributes yet public void ProxyPropertyReflectionReturnsAttributes() { IInstanceInterceptor interceptor = new InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target); PropertyInfo nameProp = proxy.GetType().GetProperty("Name"); SampleAttribute attr = (SampleAttribute)Attribute.GetCustomAttribute(nameProp, typeof(SampleAttribute)); Assert.AreEqual("A name", attr.Name); }
public void ReflectingOverProxyTypeReturnsProperties() { IInstanceInterceptor interceptor = new InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target); List <PropertyInfo> interfaceProperties = new List <PropertyInfo>(typeof(IHaveSomeProperties).GetProperties()); List <PropertyInfo> proxyProperties = new List <PropertyInfo>(proxy.GetType().GetProperties()); Assert.AreEqual(interfaceProperties.Count, proxyProperties.Count); }
public void CanAddHandlersToPipeline() { MethodInfo methodOne = typeof(ClassWithDefaultCtor).GetMethod("MethodOne"); ClassWithDefaultCtor instance = WireupHelper.GetInterceptingInstance <ClassWithDefaultCtor>(); IInterceptingProxy pm = (IInterceptingProxy)instance; CallCountHandler handler = new CallCountHandler(); HandlerPipeline pipeline = new HandlerPipeline(new CallCountHandler[] { handler }); pm.SetPipeline(methodOne, pipeline); }
private void ApplyPolicies(IInterceptor interceptor, IInterceptingProxy proxy, object target, PolicySet policies) { PipelineManager manager = new PipelineManager(); foreach (MethodImplementationInfo method in interceptor.GetInterceptableMethods(target.GetType(), target.GetType())) { HandlerPipeline pipeline = new HandlerPipeline(policies.GetHandlersFor(method, container)); manager.SetPipeline(method.ImplementationMethodInfo, pipeline); } proxy.AddInterceptionBehavior(new PolicyInjectionBehavior(manager)); }
public void AssortedParameterKindsAreProperlyHandled() { var interceptor = new TransparentProxyInterceptor(); var target = new AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds(); IInterceptingProxy proxy = interceptor.CreateProxy( typeof(AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds), target); AssortedParameterKindsAreProperlyHandledHelper.PerformTest(proxy); }
internal static T GetInterceptedInstance <T>(string methodName, ICallHandler handler) { MethodInfo method = typeof(T).GetMethod(methodName); T instance = GetInterceptingInstance <T>(); IInterceptingProxy pm = (IInterceptingProxy)instance; pm.SetPipeline(method, new HandlerPipeline(Seq.Collect(handler))); return(instance); }
public static object ThroughProxyWithAdditionalInterfaces( Type interceptedType, object target, IInstanceInterceptor interceptor, IEnumerable <IInterceptionBehavior> interceptionBehaviors, IEnumerable <Type> additionalInterfaces) { Guard.ArgumentNotNull(interceptedType, "interceptedType"); Guard.ArgumentNotNull(target, "target"); Guard.ArgumentNotNull(interceptor, "interceptor"); Guard.ArgumentNotNull(interceptionBehaviors, "interceptionBehaviors"); Guard.ArgumentNotNull(additionalInterfaces, "additionalInterfaces"); if (!interceptor.CanIntercept(interceptedType)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.InterceptionNotSupported, interceptedType.FullName), "interceptedType"); } var behaviors = interceptionBehaviors.ToList(); if (behaviors.Where(ib => ib == null).Count() > 0) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NullBehavior), "interceptionBehaviors"); } var activeBehaviors = behaviors.Where(ib => ib.WillExecute).ToList(); var allAdditionalInterfaces = GetAllAdditionalInterfaces(activeBehaviors, additionalInterfaces).ToList(); // If no behaviors and no extra interfaces, nothing to do. if (activeBehaviors.Count == 0 && allAdditionalInterfaces.Count == 0) { return(target); } IInterceptingProxy proxy = interceptor.CreateProxy(interceptedType, target, allAdditionalInterfaces.ToArray()); foreach (IInterceptionBehavior interceptionBehavior in activeBehaviors) { proxy.AddInterceptionBehavior(interceptionBehavior); } return(proxy); }
public void InterceptorCreatesProxyInstance() { IInstanceInterceptor interceptor = new InterfaceInterceptor(); ImplementsInterfaceOne target = new ImplementsInterfaceOne(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IInterfaceOne), target); IInterfaceOne intercepted = (IInterfaceOne)proxy; intercepted.TargetMethod(); Assert.IsTrue(target.TargetMethodCalled); }
public void ProxyInterceptsEvents() { IInstanceInterceptor interceptor = new InterfaceInterceptor(); ClassWithEvents target = new ClassWithEvents(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IDoEvents), target); CallCountInterceptionBehavior interceptionBehavior = new CallCountInterceptionBehavior(); proxy.AddInterceptionBehavior(interceptionBehavior); ((IDoEvents)proxy).SomeEvent += (s, a) => { }; Assert.AreEqual(1, interceptionBehavior.CallCount); }
public void AssortedParameterKindsAreProperlyHandled() { IInstanceInterceptor interceptor = new InterfaceInterceptor(); AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds target = new AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds(); IInterceptingProxy proxy = interceptor.CreateProxy( typeof(AssortedParameterKindsAreProperlyHandledHelper.ITypeWithAssertedParameterKinds), target); AssortedParameterKindsAreProperlyHandledHelper.PerformTest(proxy); }
SignatureTestTarget GetTarget() { TransparentProxyInterceptor interceptor = new TransparentProxyInterceptor(); PolicySet policySet = GetPolicies(); SignatureTestTarget target = new SignatureTestTarget(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(SignatureTestTarget), target); foreach (MethodImplementationInfo method in interceptor.GetInterceptableMethods(typeof(SignatureTestTarget), typeof(SignatureTestTarget))) { HandlerPipeline pipeline = new HandlerPipeline( policySet.GetHandlersFor(method, container)); proxy.SetPipeline(method.ImplementationMethodInfo, pipeline); } return((SignatureTestTarget)proxy); }
internal static T GetInterceptedInstance <T>(string methodName, ICallHandler handler) { MethodInfo method = typeof(T).GetMethod(methodName); T instance = GetInterceptingInstance <T>(); PipelineManager manager = new PipelineManager(); manager.SetPipeline(method, new HandlerPipeline(Sequence.Collect(handler))); IInterceptingProxy pm = (IInterceptingProxy)instance; pm.AddInterceptionBehavior(new PolicyInjectionBehavior(manager)); return(instance); }
public void HandlersCanChangeInputsBeforeTargetIsCalled() { TransparentProxyInterceptor factory = new TransparentProxyInterceptor(); PolicySet policies = GetPolicies(); CanChangeParametersTarget target = new CanChangeParametersTarget(); IInterceptingProxy proxy = factory.CreateProxy(typeof(CanChangeParametersTarget), target); ApplyPolicies(factory, proxy, target, policies); CanChangeParametersTarget intercepted = (CanChangeParametersTarget)proxy; Assert.AreEqual(0, intercepted.MostRecentInput); intercepted.DoSomething(2); Assert.AreEqual(4, intercepted.MostRecentInput); }
public void CanInterceptMethodsThroughProxy() { CallCountInterceptionBehavior interceptor = new CallCountInterceptionBehavior(); MBROWithOneMethod original = new MBROWithOneMethod(); MBROWithOneMethod intercepted = new InterceptingRealProxy(original, typeof(MBROWithOneMethod)) .GetTransparentProxy() as MBROWithOneMethod; IInterceptingProxy proxy = (IInterceptingProxy)intercepted; proxy.AddInterceptionBehavior(interceptor); int result = intercepted.DoSomething(5); Assert.AreEqual(5 * 3, result); Assert.AreEqual(1, interceptor.CallCount); }
public void HandlersCanChangeRefsAfterTargetReturns() { TransparentProxyInterceptor factory = new TransparentProxyInterceptor(); PolicySet policies = GetPolicies(); CanChangeParametersTarget target = new CanChangeParametersTarget(); IInterceptingProxy proxy = factory.CreateProxy(typeof(CanChangeParametersTarget), target); ApplyPolicies(factory, proxy, target, policies); CanChangeParametersTarget intercepted = (CanChangeParametersTarget)proxy; int output = 3; intercepted.DoSomethingElseWithRef(2, ref output); Assert.AreEqual((2 + 3 + 5) * 3, output); }
public void CanInterceptGenericMethodOnInterface() { var interceptor = new CallCountInterceptionBehavior(); var original = new ObjectWithGenericMethod(); var intercepted = new InterceptingRealProxy(original, typeof(IInterfaceWithGenericMethod)) .GetTransparentProxy() as IInterfaceWithGenericMethod; IInterceptingProxy proxy = (IInterceptingProxy)intercepted; proxy.AddInterceptionBehavior(interceptor); var result = intercepted.GetTypeName(6); Assert.AreEqual("Int32", result); Assert.AreEqual(1, interceptor.CallCount); }
public void CallingMethodInvokesHandlers() { MethodInfo methodOne = typeof(ClassWithDefaultCtor).GetMethod("MethodOne"); ClassWithDefaultCtor instance = WireupHelper.GetInterceptingInstance <ClassWithDefaultCtor>(); IInterceptingProxy pm = (IInterceptingProxy)instance; CallCountHandler handler = new CallCountHandler(); PostCallCountHandler postHandler = new PostCallCountHandler(); HandlerPipeline pipeline = new HandlerPipeline(new ICallHandler[] { postHandler, handler }); pm.SetPipeline(methodOne, pipeline); instance.MethodOne(); Assert.AreEqual(1, handler.CallCount); Assert.AreEqual(1, postHandler.CallsCompleted); }
public void CanInterceptMethodsThroughProxy() { MethodInfo doSomething = typeof(MBROWithOneMethod).GetMethod("DoSomething"); CallCountHandler handler = new CallCountHandler(); MBROWithOneMethod original = new MBROWithOneMethod(); MBROWithOneMethod intercepted = new InterceptingRealProxy(original, typeof(MBROWithOneMethod)) .GetTransparentProxy() as MBROWithOneMethod; IInterceptingProxy proxy = (IInterceptingProxy)intercepted; proxy.SetPipeline(doSomething, new HandlerPipeline(Seq.Collect <ICallHandler>(handler))); int result = intercepted.DoSomething(5); Assert.AreEqual(5 * 3, result); Assert.AreEqual(1, handler.CallCount); }
public void InterceptorCanInterceptProxyInstances() { CallCountInterceptionBehavior callCounter = new CallCountInterceptionBehavior(); ProxiedInterfaceImpl impl = new ProxiedInterfaceImpl(); IProxiedInterface instance = (IProxiedInterface) new MyProxy(typeof(IProxiedInterface), impl).GetTransparentProxy(); IInstanceInterceptor interceptor = new InterfaceInterceptor(); IInterceptingProxy proxy = (IInterceptingProxy)interceptor.CreateProxy(typeof(IProxiedInterface), (IProxiedInterface)instance); proxy.AddInterceptionBehavior(callCounter); IProxiedInterface inter = (IProxiedInterface)proxy; Assert.AreEqual("hello world", inter.DoSomething()); Assert.AreEqual(1, callCounter.CallCount); }
public void GenericWrapperWorks() { PostCallCountHandler handler = new PostCallCountHandler(); InterceptingGenericClass <DateTime> instance = new WrapperGeneric <DateTime>(); IInterceptingProxy pm = (IInterceptingProxy)instance; MethodBase reverse = typeof(InterceptingGenericClass <DateTime>).GetMethod("Reverse"); pm.SetPipeline(reverse, new HandlerPipeline(Seq.Collect <ICallHandler>(handler))); DateTime now = DateTime.Now; string result = instance.Reverse(137); Assert.AreEqual("731", result); Assert.AreEqual(1, handler.CallsCompleted); }
public static void PerformTest(IInterceptingProxy proxy) { Mock<IInterceptionBehavior> behavior = new Mock<IInterceptionBehavior>(); behavior.Setup(p => p.WillExecute).Returns(true); behavior.Setup(p => p.GetRequiredInterfaces()).Returns(Type.EmptyTypes); int argumentsCount = 0; object[] argumentsValuesByIndex = null; string[] argumentsNames = null; object[] argumentsValuesByName = null; int inputsCount = 0; object[] inputsValuesByIndex = null; string[] inputsNames = null; object[] inputsValuesByName = null; int outputsCount = 0; object[] outputsValuesByIndex = null; string[] outputsNames = null; object[] outputsValuesByName = null; object originalReturnValue = null; behavior.Setup(p => p.Invoke(It.IsAny<IMethodInvocation>(), It.IsAny<GetNextInterceptionBehaviorDelegate>())) .Returns((IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) => { argumentsCount = input.Arguments.Count; argumentsValuesByIndex = Enumerable.Range(0, argumentsCount).Select(pi => input.Arguments[pi]).ToArray(); argumentsNames = Enumerable.Range(0, argumentsCount).Select(pi => input.Arguments.GetParameterInfo(pi).Name).ToArray(); argumentsValuesByName = argumentsNames.Select(an => input.Arguments[an]).ToArray(); inputsCount = input.Inputs.Count; inputsValuesByIndex = Enumerable.Range(0, inputsCount).Select(pi => input.Inputs[pi]).ToArray(); inputsNames = Enumerable.Range(0, inputsCount).Select(pi => input.Inputs.GetParameterInfo(pi).Name).ToArray(); inputsValuesByName = inputsNames.Select(an => input.Inputs[an]).ToArray(); input.Inputs["param1"] = 11; input.Inputs[1] = 13; input.Inputs["param4"] = 14; input.Inputs[3] = 15; var result = getNext()(input, getNext); outputsCount = result.Outputs.Count; outputsValuesByIndex = Enumerable.Range(0, outputsCount).Select(pi => result.Outputs[pi]).ToArray(); outputsNames = Enumerable.Range(0, outputsCount).Select(pi => result.Outputs.GetParameterInfo(pi).Name).ToArray(); outputsValuesByName = outputsNames.Select(an => result.Outputs[an]).ToArray(); originalReturnValue = result.ReturnValue; result.Outputs[0] = 82; result.Outputs["param4"] = 84; result.ReturnValue = 100; return result; }); proxy.AddInterceptionBehavior(behavior.Object); int param2, param4; param4 = 4; var returnValue = ((ITypeWithAssertedParameterKinds)proxy).DoSomething(1, out param2, 3, ref param4, 5); Assert.AreEqual(100, returnValue); Assert.AreEqual(82, param2); Assert.AreEqual(84, param4); Assert.AreEqual(5, argumentsCount); CollectionAssert.AreEqual(new[] { 1, 0, 3, 4, 5 }, argumentsValuesByIndex); CollectionAssert.AreEqual(new[] { "param1", "param2", "param3", "param4", "param5" }, argumentsNames); CollectionAssert.AreEqual(new[] { 1, 0, 3, 4, 5 }, argumentsValuesByName); Assert.AreEqual(4, inputsCount); CollectionAssert.AreEqual(new[] { 1, 3, 4, 5 }, inputsValuesByIndex); CollectionAssert.AreEqual(new[] { "param1", "param3", "param4", "param5" }, inputsNames); CollectionAssert.AreEqual(new[] { 1, 3, 4, 5 }, inputsValuesByName); Assert.AreEqual(2, outputsCount); CollectionAssert.AreEqual(new[] { 25, 39 }, outputsValuesByIndex); CollectionAssert.AreEqual(new[] { "param2", "param4" }, outputsNames); CollectionAssert.AreEqual(new[] { 25, 39 }, outputsValuesByName); Assert.AreEqual(11 + 25 + 13 + 39 + 15, originalReturnValue); }