【发布时间】:2014-08-22 04:56:51
【问题描述】:
我在我的 asp.net mvc 4 项目中使用 Simple Injector。
我不知道如何将 Simple Injector 与城堡代理拦截器一起使用。
【问题讨论】:
标签: c# simple-injector castle-dynamicproxy
我在我的 asp.net mvc 4 项目中使用 Simple Injector。
我不知道如何将 Simple Injector 与城堡代理拦截器一起使用。
【问题讨论】:
标签: c# simple-injector castle-dynamicproxy
事实上,Simple Injector documentation 中有一个 section about Interception,它非常清楚地描述了如何进行拦截。那里给出的代码示例没有显示如何使用 Castle DynamicProxy,但实际上您需要更改几行代码才能使其正常工作。
如果你使用Interception Extensions code snippet,要让它工作,你只需要删除IInterceptor和IInvocation接口,在文件顶部添加一个using Castle.DynamicProxy,并替换通用的Interceptor带有以下内容:
public static class Interceptor
{
private static readonly ProxyGenerator generator = new ProxyGenerator();
public static object CreateProxy(Type type, IInterceptor interceptor,
object target)
{
return generator.CreateInterfaceProxyWithTarget(type, target, interceptor);
}
}
但至少,这将是您使用 Castle DynamicProxy 进行拦截所需的代码:
using System;
using System.Linq.Expressions;
using Castle.DynamicProxy;
using SimpleInjector;
public static class InterceptorExtensions
{
private static readonly ProxyGenerator generator = new ProxyGenerator();
private static readonly Func<Type, object, IInterceptor, object> createProxy =
(p, t, i) => generator.CreateInterfaceProxyWithTarget(p, t, i);
public static void InterceptWith<TInterceptor>(this Container c,
Predicate<Type> predicate)
where TInterceptor : class, IInterceptor
{
c.ExpressionBuilt += (s, e) =>
{
if (predicate(e.RegisteredServiceType))
{
e.Expression = Expression.Convert(
Expression.Invoke(
Expression.Constant(createProxy),
Expression.Constant(e.RegisteredServiceType, typeof(Type)),
e.Expression,
c.GetRegistration(typeof(TInterceptor), true).BuildExpression()),
e.RegisteredServiceType);
}
};
}
}
这是如何使用它:
container.InterceptWith<MonitoringInterceptor>(
type => type.IsInterface && type.Name.EndsWith("Repository"));
这允许拦截名称以“Repository”结尾的所有接口注册,并使用瞬态MonitoringInterceptor 进行拦截。
【讨论】: