如何将Castle.DynamicProxy拦截器改写为长尾?
- 内容介绍
- 文章标签
- 相关推荐
本文共计732个文字,预计阅读时间需要3分钟。
在ASP.NET MVC或ASP.NET Mini API中,若想在请求前后添加一层过滤器,实现验证、过滤等作用,是否可以在Service的方法前后添加一层呢?下面介绍使用Castle.DynamicProxy的方法。
首先,引入Castle.C:
csharpusing Castle.Core;using Castle.DynamicProxy;
然后,创建一个接口或类,用于定义代理逻辑:
csharppublic interface IMyService{ void MyMethod();}
public class MyService : IMyService{ public void MyMethod() { // 实现方法逻辑 }}
接下来,创建一个代理生成器,并实现拦截器:
csharppublic class MyInterceptor : IInterceptor{ public void Intercept(IInvocation invocation) { // 在请求前执行逻辑 Console.WriteLine(Before method call);
// 调用原始方法 invocation.Proceed();
// 在请求后执行逻辑 Console.WriteLine(After method call); }}
最后,使用代理生成器生成代理实例,并替换原始实例:
csharppublic static void Main(string[] args){ var proxyGenerator=new ProxyGenerator(); var proxy=proxyGenerator.CreateProxyInstance( new StandardInterceptorFactory(new MyInterceptor()), typeof(IMyService));
IMyService service=(IMyService)proxy; service.MyMethod();}
运行程序,输出结果:
Before method callAfter method call
这样,就在Service的方法前后添加了一层代理,实现了请求前后的逻辑处理。
在asp.netmvc或asp.netminiapi中,有过滤器,可以在请求前或后增加一层,达到验证,过滤等作用,如果在Service的方法前后加一层呢?这里介绍一下Castle.DynamicProxy的用法。
首先引入
Castle.Core
实现代码相对轻量:
using Castle.DynamicProxy;
using Microsoft.Extensions.DependencyInjection.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddInterceptedSingleton<ITestService, TestService, AddLogInterceptor>();
var app = builder.Build();
app.MapGet("/test", (ITestService test) =>
{
app.Logger.LogInformation("/test开始");
var result = test.Get(121);
app.Logger.LogInformation("/test结束");
return result;
});
app.Run();
public interface ITestService
{
string Get(int id);
}
public class TestService : ITestService
{
private readonly ILogger<TestService> _logger;
public TestService(ILogger<TestService> logger)
{
_logger = logger;
}
public string Get(int id)
{
_logger.LogInformation("TestService.Get({id})", id);
return "OK";
}
}
public class AddLogInterceptor : IInterceptor
{
private readonly ILogger<AddLogInterceptor> _logger;
public AddLogInterceptor(ILogger<AddLogInterceptor> logger)
{
_logger = logger;
}
public void Intercept(IInvocation invocation)
{
//用invocation可以获取被调用对象和方法的信息
_logger.LogInformation("开始调用{name},参数:{args}", invocation.Method.Name, string.Join(",", invocation.Arguments));
invocation.Proceed();
_logger.LogInformation("结束调用{name},返回结果:{result}", invocation.Method.Name, invocation.ReturnValue);
}
}
public static class InterceptedExpansion
{
public static void AddInterceptedSingleton<TIService, TService, TInterceptor>(this IServiceCollection services)
where TIService : class
where TService : class, TIService
where TInterceptor : class, IInterceptor
{
services.TryAddSingleton<IProxyGenerator, ProxyGenerator>();
services.AddSingleton<TService>();
services.TryAddTransient<TInterceptor>();
services.AddSingleton(provider =>
{
var proxyGenerator = provider.GetRequiredService<IProxyGenerator>();
var service = provider.GetRequiredService<TService>();
var interceptor = provider.GetRequiredService<TInterceptor>();
return proxyGenerator.CreateInterfaceProxyWithTarget<TIService>(service, interceptor);
});
}
}
效果如下:
想要更快更方便的了解相关知识,可以关注微信公众号
本文共计732个文字,预计阅读时间需要3分钟。
在ASP.NET MVC或ASP.NET Mini API中,若想在请求前后添加一层过滤器,实现验证、过滤等作用,是否可以在Service的方法前后添加一层呢?下面介绍使用Castle.DynamicProxy的方法。
首先,引入Castle.C:
csharpusing Castle.Core;using Castle.DynamicProxy;
然后,创建一个接口或类,用于定义代理逻辑:
csharppublic interface IMyService{ void MyMethod();}
public class MyService : IMyService{ public void MyMethod() { // 实现方法逻辑 }}
接下来,创建一个代理生成器,并实现拦截器:
csharppublic class MyInterceptor : IInterceptor{ public void Intercept(IInvocation invocation) { // 在请求前执行逻辑 Console.WriteLine(Before method call);
// 调用原始方法 invocation.Proceed();
// 在请求后执行逻辑 Console.WriteLine(After method call); }}
最后,使用代理生成器生成代理实例,并替换原始实例:
csharppublic static void Main(string[] args){ var proxyGenerator=new ProxyGenerator(); var proxy=proxyGenerator.CreateProxyInstance( new StandardInterceptorFactory(new MyInterceptor()), typeof(IMyService));
IMyService service=(IMyService)proxy; service.MyMethod();}
运行程序,输出结果:
Before method callAfter method call
这样,就在Service的方法前后添加了一层代理,实现了请求前后的逻辑处理。
在asp.netmvc或asp.netminiapi中,有过滤器,可以在请求前或后增加一层,达到验证,过滤等作用,如果在Service的方法前后加一层呢?这里介绍一下Castle.DynamicProxy的用法。
首先引入
Castle.Core
实现代码相对轻量:
using Castle.DynamicProxy;
using Microsoft.Extensions.DependencyInjection.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddInterceptedSingleton<ITestService, TestService, AddLogInterceptor>();
var app = builder.Build();
app.MapGet("/test", (ITestService test) =>
{
app.Logger.LogInformation("/test开始");
var result = test.Get(121);
app.Logger.LogInformation("/test结束");
return result;
});
app.Run();
public interface ITestService
{
string Get(int id);
}
public class TestService : ITestService
{
private readonly ILogger<TestService> _logger;
public TestService(ILogger<TestService> logger)
{
_logger = logger;
}
public string Get(int id)
{
_logger.LogInformation("TestService.Get({id})", id);
return "OK";
}
}
public class AddLogInterceptor : IInterceptor
{
private readonly ILogger<AddLogInterceptor> _logger;
public AddLogInterceptor(ILogger<AddLogInterceptor> logger)
{
_logger = logger;
}
public void Intercept(IInvocation invocation)
{
//用invocation可以获取被调用对象和方法的信息
_logger.LogInformation("开始调用{name},参数:{args}", invocation.Method.Name, string.Join(",", invocation.Arguments));
invocation.Proceed();
_logger.LogInformation("结束调用{name},返回结果:{result}", invocation.Method.Name, invocation.ReturnValue);
}
}
public static class InterceptedExpansion
{
public static void AddInterceptedSingleton<TIService, TService, TInterceptor>(this IServiceCollection services)
where TIService : class
where TService : class, TIService
where TInterceptor : class, IInterceptor
{
services.TryAddSingleton<IProxyGenerator, ProxyGenerator>();
services.AddSingleton<TService>();
services.TryAddTransient<TInterceptor>();
services.AddSingleton(provider =>
{
var proxyGenerator = provider.GetRequiredService<IProxyGenerator>();
var service = provider.GetRequiredService<TService>();
var interceptor = provider.GetRequiredService<TInterceptor>();
return proxyGenerator.CreateInterfaceProxyWithTarget<TIService>(service, interceptor);
});
}
}
效果如下:
想要更快更方便的了解相关知识,可以关注微信公众号

