我已经使用 CaSTLe.DynamicProxy 和 StructureMap 2.6 API 进行了拦截,但现在无法使用 StructureMap 3.0 进行拦截。谁能帮我找到更新的文档甚至演示?我发现的一切似乎都与旧版本有关。例如StructureMap.Interceptors.TypeInterceptor 接口(interface)等
最佳答案
哈哈哈!我他妈的做到了!方法如下:
public class ServiceSingletonConvention : DefaultConventionScanner
{
public override void Process(Type type, Registry registry)
{
base.Process(type, registry);
if (type.IsInterface || !type.Name.ToLower().EndsWith("service")) return;
var pluginType = FindPluginType(type);
var delegateType = typeof(Func<,>).MakeGenericType(pluginType, pluginType);
// Create FuncInterceptor class with generic argument +
var d1 = typeof(FuncInterceptor<>);
Type[] typeArgs = { pluginType };
var interceptorType = d1.MakeGenericType(typeArgs);
// -
// Create lambda expression for passing it to the FuncInterceptor constructor +
var arg = Expression.Parameter(pluginType, "x");
var method = GetType().GetMethod("GetProxy").MakeGenericMethod(pluginType);
// Crate method calling expression
var methodCall = Expression.Call(method, arg);
// Create the lambda expression
var lambda = Expression.Lambda(delegateType, methodCall, arg);
// -
// Create instance of the FuncInterceptor
var interceptor = Activator.CreateInstance(interceptorType, lambda, "");
registry.For(pluginType).Singleton().Use(type).InterceptWith(interceptor as IInterceptor);
}
public static T GetProxy<T>(object service)
{
var proxyGeneration = new ProxyGenerator();
var result = proxyGeneration.CreateInterfaceProxyWithTarget(
typeof(T),
service,
(Castle.DynamicProxy.IInterceptor)(new MyInterceptor())
);
return (T)result;
}
}
这里的问题是 SM 3.* 允许拦截已知类型,即执行以下操作:
expression.For<IService>().Use<Service>().InterceptWith(new FuncInterceptor<IService>(service => GetProxyFrom(service)));
但是,如果您想在自定义扫描约定中包含拦截逻辑,您想拦截具有特定签名的所有类型实例(在我的例子中,类型的名称以“服务”结尾),该怎么办?
这就是我使用 Expression API 和反射所完成的。
另外,我在这里使用 CaSTLe.DinamicProxy 为我的服务创建代理对象。
希望其他人会觉得这很有帮助:)
关于dependency-injection - 使用 StructureMap 3.* 进行拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23593914/