1

我有以下代码:

_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 中进行接线

4

2 回答 2

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);
    }
}

我对结果很满意。

于 2012-12-20T12:44:11.697 回答
0

我在这里可能完全错了,但这不是诀窍吗?

For<IPersonManager>()
    .EnrichAllWith(t => proxyGenerator.CreateInterfaceProxyWithTarget(
        t, _container.GetInstance<AuthenticationInterceptor>()))
    .Use<PersonManager>();
于 2012-12-20T09:41:50.483 回答