Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System.Runtime.CompilerServices;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;


namespace ResolvingWithPolicyInjection
{
    /// <summary>
    /// Extensions methods for UnityContainer
    /// </summary>
    public static class UnityContainerExtensionMethods
    {
        /// <summary>
        /// Resolves T and wrapps it with policy injection
        /// </summary>
        /// <typeparam name="T">the type to resolve</typeparam>
        /// <param name="unityContainer">the container the resolving should be done against</param>
        /// <returns>a resolved object wrapped with Policy Injection</returns>
        /// <remarks></remarks>
        public static T ResolveWithPolicyInjection<T>(this UnityContainer unityContainer)
        {
            // Resolve from container
            var resolved = unityContainer.Resolve<T>();

            // Wrappa with policy injection
            return PolicyInjection.Wrap<T>(resolved);
        }

        /// <summary>
        /// Registers a type to be resolved to another 
        /// AND configures policy injection for the type if so configured in app.config
        /// </summary>
        /// <typeparam name="TFrom">type to resolve from</typeparam>
        /// <typeparam name="TTo">type to resolve to</typeparam>
        /// <param name="unityContainer">the container the resolving should be done against</param>
        public static void RegisterTypeWithPolicyInjection<TFrom, TTo>(this UnityContainer unityContainer) where TTo : TFrom
        {
            // Check if policies are configured
            var configSource = ConfigurationSourceFactory.Create();
            var policyInjectionSection = configSource.GetSection(PolicyInjectionSettings.SectionName);
            var policySettings = (PolicyInjectionSettings)policyInjectionSection;

            // add policy settings, if any, to the container
            if ((policySettings != null))
            {
                policySettings.ConfigureContainer(unityContainer, configSource);
            }

            // Set up the container with interception
            unityContainer.Configure<Interception>().SetInterceptorFor<TFrom>(new TransparentProxyInterceptor());

            // Finally register the type in the container - as normal
            unityContainer.RegisterType<TFrom, TTo>();
        }
    }
}