gpt4 book ai didi

c# - 使用带有 CaSTLe 代理拦截器的简单注入(inject)器

转载 作者:太空狗 更新时间:2023-10-29 17:39:08 25 4
gpt4 key购买 nike

我在我的 asp.net mvc 4 项目中使用 Simple Injector。

我不知道如何将 Simple Injector 与城堡代理拦截器一起使用。

最佳答案

实际上有一个 section about Interception在简单注入(inject)器中 documentation这非常清楚地描述了如何进行拦截。那里给出的代码示例没有显示如何使用 CaSTLe DynamicProxy,但实际上您需要更改几行代码才能使其正常工作。

如果您使用 Interception Extensions code snippet ,要让它工作,你只需要删除 IInterceptorIInvocation 接口(interface),在文件顶部添加一个 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”结尾的所有接口(interface)注册,以使用 transient MonitoringInterceptor 进行拦截。

关于c# - 使用带有 CaSTLe 代理拦截器的简单注入(inject)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24513530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com