.NET Core 2中使用Castle DynamicProxy进行Autofac方法级别的拦截 [英] Autofac method level interception with Castle DynamicProxy in .NET Core 2
问题描述
我目前写了一个代码在下面的拦截器
I currently wrote an Interceptor which code is below
public class TransactionalInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
using (var transaction = ...)
{
try
{
invocation.Proceed();
transaction.Commit();
}
catch
{
transaction.Rollback();
}
finally
{
transaction.Dispose();
}
}
}
}
但是注册此拦截器时,它将应用于所有方法.我有一个服务类,其中注入了具有CRUD方法的存储库.我不希望为查询方法打开事务.
but when register this interceptor it will apply to all methods. I have a service class with a repository injected having CRUD methods. I don't want a transaction to be opened for query methods.
我阅读了此链接,但无法弄清楚如何将其应用于我的代码 http://docs.autofac.org/en/latest/advanced/adapters-decorators.html#decorators
I read this link but I cannot figure out how to apply it to my code http://docs.autofac.org/en/latest/advanced/adapters-decorators.html#decorators
我不知道谁可以重构我的TransactionalInterceptor(并注册它)以在此类代码中使用它
I don't know who to refactor my TransactionalInterceptor (and register it) to use it in a class like this code
[Intercept(typeof(LoggerInterceptor))] //logger
public class SomeService : ISomeService
{
private readonly ISomeRepository someRepository;
public SomeService(SomeRepository someRepository)
{
this.someRepository = someRepository;
}
public IEnumerable<SomeDto> GetAll()
{
// code
}
public SomeDto GetById()
{
// code
}
[Transactional]
public int Create(SomeDto someDto)
{
// code to insert
}
}
推荐答案
Intercept
方法的 invocation
参数包含一个 Method
属性,是当前拦截的方法的 MethodInfo
.
The invocation
parameter of the Intercept
method contains a Method
property which is a MethodInfo
of the method currently intercepted.
您可以使用此属性执行所需的操作.
You can use this property to do what you want.
例如,使用方法名称:
public void Intercept(IInvocation invocation)
{
if (invocation.MethodInvocationTarget.Name != nameof(ISomeService.Create))
{
invocation.Proceed();
return;
}
using (var transaction = ...)
{
try
{
invocation.Proceed();
transaction.Commit();
}
catch
{
transaction.Rollback();
}
finally
{
transaction.Dispose();
}
}
}
或基于目标方法的属性:
or based on an attribute from the target method :
if (!invocation.MethodInvocationTarget
.CustomAttributes
.Any(a => a.AttributeType == typeof(TransactionalAttribute)))
您还可以使用 IInterceptorSelector
类型,但是要在 Autofac
You can also use the IInterceptorSelector
type but it requires more work to register it with Autofac
这篇关于.NET Core 2中使用Castle DynamicProxy进行Autofac方法级别的拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!