Tsahi
Tsahi

Reputation: 455

Intercept all classes in application with Unity

I want to use interceptor in my application in order to do logging. Of course I could register each type with interceptor like this:

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

but since I have a lot of types I was wondering if there's a cleaner way to do this for all my classes?

Upvotes: 0

Views: 336

Answers (1)

TylerOhlsen
TylerOhlsen

Reputation: 5578

Here's a method that will enable interception on all types that have already been registered. So call this after your registrations are complete. Then you can use Policy Injection to hook up the interceptors you want to use.

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

Upvotes: 2

Related Questions