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