15

我有一个使用 Structuremap 的 ASP MVC 4 应用程序。我正在尝试通过 Structuremap 拦截将日志记录添加到我的应用程序中。在注册表中,我扫描一个特定的程序集,以便使用默认约定注册它的所有类型:

public class ServicesRegistry : Registry
{
    public ServicesRegistry()
    {
        Scan(x =>
        {
            x.AssemblyContainingType<MyMarkerService>();
            x.WithDefaultConventions();
        });
    }
}

拦截器:

public class LogInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        var watch = Stopwatch.StartNew();
        invocation.Proceed();
        watch.Stop();//log the time
    }
}

我可以为一种特定的插件类型添加拦截器,如下所示:

var proxyGenerator = new ProxyGenerator();
container.Configure(x => x.For<IServiceA>().Use<ServiceA>().DecorateWith(instance => proxyGenerator.CreateInterfaceProxyWithTarget(instance, new LogInterceptor())));

但我想让结构映射为注册表中扫描的所有类型创建日志代理。有没有办法做到这一点?

4

1 回答 1

9

看起来这没有一个简单的扩展点,但是我使用自定义约定使用了一个相当不错的解决方案。为了帮助您理解我所做的决定,我将引导您完成几个步骤(跳过我在途中犯的许多错误)。

首先让我们看看您已经在使用的 DefaultConvention。

默认约定:

 public class DefaultConventionScanner : ConfigurableRegistrationConvention
{
    public override void Process(Type type, Registry registry)
    {
        if (!TypeExtensions.IsConcrete(type))
            return;
        Type pluginType = this.FindPluginType(type);
        if (pluginType == null || !TypeExtensions.HasConstructors(type))
            return;
        registry.AddType(pluginType, type);
        this.ConfigureFamily(registry.For(pluginType, (ILifecycle)null));
    }

    public virtual Type FindPluginType(Type concreteType)
    {
        string interfaceName = "I" + concreteType.Name;
        return Enumerable.FirstOrDefault<Type>((IEnumerable<Type>)concreteType.GetInterfaces(), (Func<Type, bool>)(t => t.Name == interfaceName));
    }
}

非常简单,我们获取类型和接口对并检查以确保它们有构造函数,如果有,我们就注册它们。最好只修改它以调用 DecorateWith,但您只能在 For<>().Use<>() 上调用它,而不是 For().Use()。

接下来让我们看看 DecorateWith 做了什么:

public T DecorateWith(Expression<Func<TPluginType, TPluginType>> handler)
{
  this.AddInterceptor((IInterceptor) new FuncInterceptor<TPluginType>(handler, (string) null));
  return this.thisInstance;
}

所以这会创建一个 FuncInterceptor 并注册它。在决定创建一个新类会更容易之前,我花了相当多的时间尝试通过反射动态地创建其中一个:

public class ProxyFuncInterceptor<T> : FuncInterceptor<T> where T : class
{
    public ProxyFuncInterceptor() : base(x => MakeProxy(x), "")
    {
    }

    protected ProxyFuncInterceptor(Expression<Func<T, T>> expression, string description = null)
        : base(expression, description)
    {
    }

    protected ProxyFuncInterceptor(Expression<Func<IContext, T, T>> expression, string description = null)
        : base(expression, description)
    {
    }

    private static T MakeProxy(T instance)
    {
        var proxyGenerator = new ProxyGenerator();
        return proxyGenerator.CreateInterfaceProxyWithTarget(instance, new LogInterceptor());
    }
}

当我们将类型作为变量时,此类只会使使用变得更容易。

最后,我根据默认约定制定了自己的约定。

public class DefaultConventionWithProxyScanner : ConfigurableRegistrationConvention
{
    public override void Process(Type type, Registry registry)
    {
        if (!type.IsConcrete())
            return;
        var pluginType = this.FindPluginType(type);
        if (pluginType == null || !type.HasConstructors())
            return;
        registry.AddType(pluginType, type);
        var policy = CreatePolicy(pluginType);
        registry.Policies.Interceptors(policy);

        ConfigureFamily(registry.For(pluginType));
    }

    public virtual Type FindPluginType(Type concreteType)
    {
        var interfaceName = "I" + concreteType.Name;
        return concreteType.GetInterfaces().FirstOrDefault(t => t.Name == interfaceName);
    }

    public IInterceptorPolicy CreatePolicy(Type pluginType)
    {
        var genericPolicyType = typeof(InterceptorPolicy<>);
        var policyType = genericPolicyType.MakeGenericType(pluginType);
        return (IInterceptorPolicy)Activator.CreateInstance(policyType, new object[]{CreateInterceptor(pluginType), null});     
    }

    public IInterceptor CreateInterceptor(Type pluginType)
    {
        var genericInterceptorType = typeof(ProxyFuncInterceptor<>);
        var specificInterceptor = genericInterceptorType.MakeGenericType(pluginType);
        return (IInterceptor)Activator.CreateInstance(specificInterceptor);
    }
}

它几乎与一个添加相同,我为我们注册的每种类型创建了一个拦截器和拦截器类型。然后我注册该策略。

最后,一些单元测试来证明它有效:

 [TestFixture]
public class Try4
{
    [Test]
    public void Can_create_interceptor()
    {
        var type = typeof (IServiceA);
        Assert.NotNull(new DefaultConventionWithProxyScanner().CreateInterceptor(type));
    }

    [Test]
    public void Can_create_policy()
    {
        var type = typeof (IServiceA);
        Assert.NotNull(new DefaultConventionWithProxyScanner().CreatePolicy(type));
    }

    [Test]
    public void Can_register_normally()
    {
        var container = new Container();
        container.Configure(x => x.Scan(y =>
        {
            y.TheCallingAssembly();
            y.WithDefaultConventions();
        }));

        var serviceA = container.GetInstance<IServiceA>();
        Assert.IsFalse(ProxyUtil.IsProxy(serviceA));
        Console.WriteLine(serviceA.GetType());
    }

    [Test]
    public void Can_register_proxy_for_all()
    {
        var container = new Container();
        container.Configure(x => x.Scan(y =>
        {
            y.TheCallingAssembly();
            y.Convention<DefaultConventionWithProxyScanner>();
        }));

        var serviceA = container.GetInstance<IServiceA>();
        Assert.IsTrue(ProxyUtil.IsProxy(serviceA));
        Console.WriteLine(serviceA.GetType());
    }

    [Test]
    public void Make_sure_I_wait()
    {
        var container = new Container();
        container.Configure(x => x.Scan(y =>
        {
            y.TheCallingAssembly();
            y.Convention<DefaultConventionWithProxyScanner>();
        }));

        var serviceA = container.GetInstance<IServiceA>();
        serviceA.Wait();
    }
}
}

 public interface IServiceA
{
    void Wait();
}

public class ServiceA : IServiceA
{
    public void Wait()
    {
       Thread.Sleep(1000);
    }
}

public interface IServiceB
{

}

public class ServiceB : IServiceB
{

}

这里肯定有一些清理空间(缓存,使其干燥,更多测试,使其更易于配置),但它可以满足您的需要,并且是一种非常合理的方式。

请询问您是否有任何其他问题。

于 2015-09-26T03:46:28.047 回答