使用 Unity 拦截应用程序中的所有 类

Intercept all classes in application with Unity

我想在我的应用程序中使用拦截器来进行日志记录。 当然我可以像这样用拦截器注册每种类型:

container.AddNewExtension<Interception>();
container.RegisterType<ITenantStore, TenantStore>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<LoggingInterceptionBehavior>());

但是因为我有很多类型,所以我想知道是否有更简洁的方法来为我的所有 类 执行此操作?

这里有一个方法可以对所有已注册的类型启用拦截。所以在你的注册完成后调用它。然后你可以使用Policy Injection来连接你想使用的拦截器。

public static class UnityContainerInterceptionExtensions
{
    public static IUnityContainer EnableInterceptionForAllRegisteredTypes
        (this IUnityContainer unityContainer)
    {
        unityContainer
            .Registrations
            .ForEach(r => unityContainer.EnableInterception(r.RegisteredType, r.Name));

        return unityContainer;
    }

    public static IUnityContainer EnableInterception<T>
        (this IUnityContainer unityContainer, string name = null)
    {
        return unityContainer.EnableInterception(typeof (T), name);
    }

    public static IUnityContainer EnableInterception
        (this IUnityContainer unityContainer, Type registrationType, string name = null)
    {
        // Don't allow interception of unity types
        if (registrationType.Namespace.StartsWith(typeof(IUnityContainer).Namespace))
            return unityContainer;

        // Don't allow interception on the intercepting call handlers
        if (typeof (ICallHandler).IsAssignableFrom(registrationType))
            return unityContainer;

        var interception = unityContainer.Configure<Interception>();

        var interfaceInterceptor = new InterfaceInterceptor();
        if (interfaceInterceptor.CanIntercept(registrationType))
        {
            interception
                .SetInterceptorFor(registrationType, name, interfaceInterceptor);
            return unityContainer;
        }

        var virtualMethodInterceptor = new VirtualMethodInterceptor();
        if (virtualMethodInterceptor.CanIntercept(registrationType))
        {
            interception
                .SetInterceptorFor(registrationType, name, virtualMethodInterceptor);
            return unityContainer;
        }

        var transparentProxyInterceptor = new TransparentProxyInterceptor();
        if (transparentProxyInterceptor.CanIntercept(registrationType))
        {
            interception
                .SetInterceptorFor(registrationType, name, transparentProxyInterceptor);
            return unityContainer;
        }

        return unityContainer;
    }
}