public FoobarInterceptor(InterceptDelegate next, IFoo foo, IBar bar, string flag) { _next = next; this.Foo = foo; this.Bar = bar; this.Flag = flag; }
protected override Task InterceptAsync(IInvocation invocation, Func <IInvocation, Task> proceed) { var invocationContext = new DynamicProxyInvocationContext(invocation); InterceptDelegate next = context => proceed(invocation); return(_interceptor(next)(invocationContext)); }
/// <summary> /// Initializes a new instance of the <see cref="ExceptionInterceptor"/> class. /// </summary> /// <param name="next">The next <see cref="InterceptDelegate"/>.</param> /// <param name="exceptionName">The name of the exception.</param> /// <param name="retriedTimes">The retried times if occurs connection exception.</param> public ExceptionInterceptor(InterceptDelegate next, string exceptionName, int retriedTimes) { Guard.ArgumentNotNull(next, nameof(next)); _retriedTimes = retriedTimes; _exceptionName = exceptionName; _next = next; }
public override void Intercept(InterceptContext context, InterceptDelegate next) { context.ToString(); //Console.WriteLine("Begin"); next(context); //Console.WriteLine("End"); }
public TestSumServiceProxy(IInterceptDelegateBuilder builder) { sumMethod = typeof(TestSumService).GetMethod("Sum", new Type[] { typeof(int), typeof(int) }); sumInterceptor = builder.BuildInterceptDelegate(sumMethod, c => { c.Result = base.Sum((int)c.Parameters[0], (int)c.Parameters[1]); }); }
public FoobarInterceptor(InterceptDelegate next, IService service, string argument) { _next = next; if (null == service || null == argument) { throw new InvalidOperationException(); } }
public virtual void Intercept(InterceptContext context, InterceptDelegate next) { NoSynchronizationContextScope.Run(InterceptAsync(context, c => { next(c); return(Task.CompletedTask); })); }
protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation, Func <IInvocation, Task <TResult> > proceed) { var invocationContext = new DynamicProxyInvocationContext(invocation); InterceptDelegate next = context => proceed(invocation); await _interceptor(next)(invocationContext); return(((Task <TResult>)invocationContext.ReturnValue).Result); }
public T Multiply <T>(T x, T y) { var method = typeof(ICalculator).GetMethod("Multiply"); var interceptor = _interceptors.GetInterceptor(method); var invoker = new TargetInvoker <T>(_target); InterceptDelegate next = new InterceptDelegate(invoker.Invoke); var arguments = new object[] { x, y }; var context = new DefaultInvocationContext(method, this, _target, arguments); interceptor(next)(context).Wait(); return((T)context.ReturnValue); }
public void New_Arguments_Not_Allow_Null(string nextIndicator, string managerIndicator) { InterceptDelegate next = nextIndicator == null ? null : (InterceptDelegate)(_ => Task.CompletedTask); ExceptionManager manager = managerIndicator == null ? null : new ExceptionManager(new Dictionary <string, IExceptionPolicy> { ["policy1"] = new ExceptionPolicy(new ExceptionPolicyEntry[0], _ => Task.CompletedTask, _ => Task.CompletedTask) }); Assert.Throws <ArgumentNullException>(() => new ExceptionHandlingInterceptor(next, manager)); }
/// <summary> /// Invoke interceptor and target method. /// </summary> /// <param name="interceptor">A <see cref="InterceptorDelegate"/> representing interceptor applied to target method.</param> /// <param name="handler">A <see cref="InterceptDelegate"/> used to invoke the target method.</param> /// <param name="context">A <see cref="InvocationContext"/> representing the current method invocation context.</param> /// <returns>The task to invoke interceptor and target method.</returns> public static Task InvokeHandler(InterceptorDelegate interceptor, InterceptDelegate handler, InvocationContext context) { async Task Wrap(InvocationContext invocationContext) { await handler(invocationContext); if (invocationContext.ReturnValue is Task task) { await task; } } return(interceptor(Wrap)(context)); }
/// <summary> /// Invoke interceptor and target method. /// </summary> /// <param name="interceptor">A <see cref="InterceptorDelegate"/> representing interceptor applied to target method.</param> /// <param name="handler">A <see cref="InterceptDelegate"/> used to invoke the target method.</param> /// <param name="context">A <see cref="InvocationContext"/> representing the current method invocation context.</param> /// <returns>The task to invoke interceptor and target method.</returns> public static Task InvokeHandler(InterceptorDelegate interceptor, InterceptDelegate handler, InvocationContext context) { InterceptDelegate wrapper = async _ => { await handler(_); var task = _.ReturnValue as Task; if (null != task) { await task; } }; return(interceptor(wrapper)(context)); }
public InterceptDelegate BuildInterceptDelegate(MethodInfo methodInfo, InterceptDelegate action) { return(syncCache.GetOrAdd(methodInfo, (m) => { var syncAction = action; var builders = boxs.Where(i => i.Verifier(m)) .Select(i => i.Interceptor) .OrderByDescending(i => i.Order) .Select <IInterceptor, Func <InterceptDelegate, InterceptDelegate> >(i => next => c => i.Intercept(c, next)); foreach (var builder in builders) { syncAction = builder(syncAction); } return syncAction; })); }
public InterceptorChainBuilder Use(Type interceptorType, int order, params object[] args) { var invokeMethod = interceptorType.GetMethods().Where(p => p.Name == "InvokeAsync" && p.ReturnType == typeof(Task) && p.GetParameters().FirstOrDefault()?.ParameterType == typeof(InvocationContext)).FirstOrDefault(); if (invokeMethod == null) { return(this); } //InvokeDelegate(object interceptor, InvocationContext context, IServiceProvider serviceProvider); ParameterExpression interceptor = Expression.Parameter(typeof(object), "interceptor"); ParameterExpression context = Expression.Parameter(typeof(InvocationContext), "context"); ParameterExpression serviceProvider = Expression.Parameter(typeof(IServiceProvider), "serviceProvider"); var invArgs = invokeMethod.GetParameters().Select(p => { if (p.ParameterType == typeof(InvocationContext)) { return((Expression)context); } Expression serviceType = Expression.Constant(p.ParameterType, typeof(Type)); Expression callGetService = Expression.Call(_getServiceMethod, serviceProvider, serviceType); return((Expression)Expression.Convert(callGetService, p.ParameterType)); }); Expression instanceConvert = Expression.Convert(interceptor, interceptorType); var invoke = Expression.Call(instanceConvert, invokeMethod, invArgs); var invoker = Expression.Lambda <InvokeDelegate>(invoke, interceptor, context, serviceProvider).Compile(); InterceptorDelegate interceptorDelegate = _next => { var instance = ActivatorUtilities.CreateInstance(this.ServiceProvider, interceptorType, _next); InterceptDelegate _ = async invContext => { await invoker(instance, invContext, this.ServiceProvider); }; return(_); }; this._interceptors.Add(order, interceptorDelegate); return(this); }
/// <summary> /// 带参构造函数 /// </summary> /// <param name="next">拦截委托</param> /// <param name="maxRetryCount">最多重试几次</param> /// <param name="retryIntervalMilliseconds">重试间隔时长,单位毫秒</param> /// <param name="isEnableBreaker">是否启用熔断</param> /// <param name="exceptionsAllowedBeforeBreaking">熔断前允许异常几次</param> /// <param name="millisecondsOfBreak">熔断多长时间</param> /// <param name="timeOutMilliseconds">执行超过多少毫秒则认为超时(0表示不检测超时)</param> /// <param name="cacheTTLMilliseconds">缓存多少毫秒(0表示不缓存),用“类名+方法名+所有参数ToString拼接”做缓存Key</param> public CacheInterceptor(InterceptDelegate next, int maxRetryCount, int retryIntervalMilliseconds, bool isEnableBreaker, int exceptionsAllowedBeforeBreaking, int millisecondsOfBreak, int timeOutMilliseconds, int cacheTTLMilliseconds) { _next = next; this.MaxRetryCount = maxRetryCount; this.RetryIntervalMilliseconds = retryIntervalMilliseconds; this.IsEnableBreaker = isEnableBreaker; this.ExceptionsAllowedBeforeBreaking = exceptionsAllowedBeforeBreaking; this.MillisecondsOfBreak = millisecondsOfBreak; this.TimeOutMilliseconds = timeOutMilliseconds; this.CacheTTLMilliseconds = cacheTTLMilliseconds; }
/// <summary> /// Base Post Class, call this if adding a new version of the post method. /// </summary> /// <param name="url">The URL.</param> /// <param name="formData">The form data.</param> /// <returns></returns> private async Task <HttpWebResponse> _post(string url, object formData, InterceptDelegate requestIntercept, int retrycount, Dictionary <string, string> headers = null, int startRetryIndex = 0) { using (var client = ApiClient) { using (var resp = await client.PostAsync <HttpWebResponse>(url, formData)) { await requestIntercept?.Invoke(resp); if (await InterceptResponse(response: resp)) { //this is to prevent endless loops, TODO: change the flow to a pipeline structure for more flexebilety? would be easily possible of we change to another rest client. if (startRetryIndex < retrycount)//TODO: think this out further, max limit of retries, should onlt be 1 for auth, but poor connection may change this mb? { return(await _post(url, formData, requestIntercept, ++startRetryIndex)); } } return(resp); } } }
public void Intercept(IInvocation invocation) { CastleInvocationContext invocationContext = new CastleInvocationContext(invocation, _serviceProvider); InterceptDelegate next = context => ((CastleInvocationContext)context).ProceedAsync(); try { _interceptor(next)(invocationContext).Wait(); } catch (AggregateException ex) { throw ex?.InnerException ?? ex; } catch { throw; } }
/// <summary> /// Invoke interceptor and target method. /// </summary> /// <param name="interceptor">A <see cref="InterceptorDelegate"/> representing interceptor applied to target method.</param> /// <param name="handler">A <see cref="InterceptDelegate"/> used to invoke the target method.</param> /// <param name="context">A <see cref="InvocationContext"/> representing the current method invocation context.</param> /// <returns>The task to invoke interceptor and target method.</returns> public static Task InvokeHandler(InterceptorDelegate interceptor, InterceptDelegate handler, InvocationContext context) { InterceptDelegate wrapper = async _ => { await handler(_); var task = _.ReturnValue as Task; if (null != task) { await task; } }; var resultTask = interceptor(wrapper)(context); // throw inner InterceptorException var agregateException = resultTask.Exception; if (agregateException != null && agregateException.InnerExceptions.Any(ex => (ex is InterceptorException) && (ex as InterceptorException).RequireThrow)) { throw resultTask.Exception; } return(resultTask); }
public MemoryCacheInterceptor(InterceptDelegate next) { _next = next; }
public FoobarInterceptorAttribute(InterceptDelegate next) { _next = next; }
public CacheInterceptor(InterceptDelegate next, IMemoryCache cache, IOptions <MemoryCacheEntryOptions> optionsAccessor) { _next = next; _cache = cache; _options = optionsAccessor.Value; }
public RequestInterceptionObject(HttpStatusCode code, InterceptDelegate codeToRun, bool retryRequest) { this.StatusCode = code; this.CodeToRun = codeToRun; this.RetryRequest = retryRequest; }
public DecorateInterceptor(InterceptDelegate next) { _next = next; }
public async Task <HttpWebResponse> Post(ApiPath path, string accessToken, object formData = null, InterceptDelegate customIntercept = null) { AccessToken = accessToken; var resp = await Post(GetFullPath(path), formData); return(resp); }
public ExceptionHandler(InterceptDelegate next, string logCategory) { _next = next; _logCategory = logCategory; }
public FoobarInterceptor(InterceptDelegate next) { _next = next; }
public RedisCacheInterceptor(InterceptDelegate next) { _next = next; }
public override void Intercept(InterceptContext context, InterceptDelegate next) { next(context); context.Result = (int)context.Result + 1; }
public LoggerInterceptor(InterceptDelegate next, ILoggerFactory loggerFactory, string category) { this.next = next; this.logger = loggerFactory.CreateLogger(category); }
public void Intercept(IInvocation invocation) { InterceptDelegate next = context => (context).ProceedAsync(); var intercepterDelegate = _interceptor(next); _interceptor(next)(new InvocationContext(invocation)).Wait(); }