我有以下代码:
_container = new Container(x => x.AddRegistry<ManagerRegistry>());
-
public class ManagerRegistry : Registry
{
public ManagerRegistry()
{
var proxyGenerator = new ProxyGenerator();
For<IPersonManager>()
.EnrichAllWith(t => proxyGenerator.CreateInterfaceProxyWithTarget(
t, new AuthenticationInterceptor()))
.Use<PersonManager>();
}
}
-
public class AuthenticationInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (!HttpContext.Current.User.IsInRole("Monkey"))
throw new Exception("Only monkeys allowed!");
invocation.Proceed();
}
}
拦截在StructureMap中创建依赖项,使用DynamicProxy 装饰 。
现在这很好用,因为拦截器本身没有依赖。
但考虑到以下因素:
public class LoggingInterceptor : IInterceptor
{
public LoggingInterceptor(ILogger logger)
{
如何如何接线 在StructureMap中?
答案 0 :(得分:2)
这就是我提出的:
_container.RegisterInterceptor<IPersonManager, LoggingInterceptor>();
-
public static class ContainerExtensions
{
public static void RegisterInterceptor<TDependency, TInterceptor>(this IContainer container)
where TDependency : class
where TInterceptor : IInterceptor
{
IInterceptor interceptor = container.GetInstance<TInterceptor>();
if (interceptor == null)
throw new NullReferenceException("interceptor");
TypeInterceptor typeInterceptor
= new GenericTypeInterceptor<TDependency>(interceptor);
container.Configure(c => c.RegisterInterceptor(typeInterceptor));
}
}
-
public class GenericTypeInterceptor<TDependency> : TypeInterceptor
where TDependency : class
{
private readonly IInterceptor _interceptor;
private readonly ProxyGenerator _proxyGenerator = new ProxyGenerator();
public GenericTypeInterceptor(IInterceptor interceptor)
{
if (interceptor == null)
throw new ArgumentNullException("interceptor");
_interceptor = interceptor;
}
public object Process(object target, IContext context)
{
return _proxyGenerator.CreateInterfaceProxyWithTarget(target as TDependency, _interceptor);
}
public bool MatchesType(Type type)
{
return typeof(TDependency).IsAssignableFrom(type);
}
}
我对结果非常满意。
答案 1 :(得分:0)
我在这里可能完全错了,但这不是诀窍吗?
For<IPersonManager>()
.EnrichAllWith(t => proxyGenerator.CreateInterfaceProxyWithTarget(
t, _container.GetInstance<AuthenticationInterceptor>()))
.Use<PersonManager>();