Showing posts with label Unity. Show all posts
Showing posts with label Unity. Show all posts

Saturday, November 16, 2013

Unity container and Factory pattern

Recently I had merged Unity container and Factory pattern to create objects in a central place. Below is the code for the same. Thought it would be useful to you guys!!

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

public class DependencyFactory
    {
        public static T GetObject()
        {
            IUnityContainer container = new UnityContainer();
            UnityConfigurationSection section =
              (UnityConfigurationSection)ConfigurationManager.GetSection(ConfigurationManager.AppSettings["UnityContainer"]);
            section.Configure(container);
            T res = container.Resolve();
            return res;
        }

        public static T GetObject(params ResolverOverride[] overrides)
        {
            IUnityContainer container = new UnityContainer();
            UnityConfigurationSection section =
              (UnityConfigurationSection)ConfigurationManager.GetSection(ConfigurationManager.AppSettings["UnityContainer"]);
            section.Configure(container);
            T res = container.Resolve(overrides);
            return res;
        }
    }


  <configuration>
   <configSections>
    <section name="TEST_UNITY"
       type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
               Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <TEST_UNITY>
    <containers>
      <container>
        <types>
          <type
             type="Unity.Sample.Repositories.IEnrollmentRepository,Unity.Sample"
             mapTo="Unity.Sample.Repositories.DummyEnrollmentRepository,
                      Unity.Sample" />
          <type
             type="Unity.Sample.Repositories.ICustomerDetailsRepository,Unity.Sample"
             mapTo="Unity.Sample.Repositories.DummyCustomerDetailsRepository,
                      Unity.Sample" />
          <type
             type="Unity.Sample.Repositories.ICustomerRepository,Unity.Sample"
             mapTo="Unity.Sample.Repositories.DummyCustomerRepository,
                      Unity.Sample" />
           <type
             type="Unity.Sample.Repositories.IBIBRepository,Unity.Sample"
             mapTo="Unity.Sample.Repositories.DummyBIBRepository,
                      Unity.Sample" />
          <type
             type="Unity.Sample.Repositories.ILockBoxRepository,Unity.Sample"
             mapTo="Unity.Sample.Repositories.DummyLockBoxRepository,
                      Unity.Sample" />
          <type
             type="Unity.Sample.Interfaces.IBIB,Unity.Sample"
             mapTo="Unity.Sample.Impl.DummyBIB,
                      Unity.Sample" />
          <type
               type="Unity.Sample.Interfaces.ILockBox,Unity.Sample"
               mapTo="Unity.Sample.Impl.DummyLockBox,
                      Unity.Sample" />
        </types>
      </container>
    </containers>
  </TEST_UNITY>
  <appSettings>
    <add key="UnityContainer" value="TEST_UNITY"/>
  </appSettings>
</configuration>
   
 

Tuesday, September 22, 2009

Custom Matching Rules and Custom Handlers using Unity Application Block


There might be times where-in you will have to write custom matching rules and the corresponding handlers to achieving auditing. Unity Application Block provides that flexibility to achieve this. Below is the code which will help to to do

Matching Rule:


 public class MethodMatchingRule : IMatchingRule
    {

string _MethodName = string.Empty;

public MethodMatchingRule(string MethodName)
{
  _MethodName =  MethodName;
}


public MethodMatchingRule()
{

}


        public bool Matches(MethodBase member)
        {
            return member.Name == _
MethodName;
        }

    }



Custom Handler:
public class DynamicHandler : ICallHandler
    {
        public int Order { get; set; }

        public DynamicHandler()
        {

        }

        public DynamicHandler(int order)
        {
            this.Order = order;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {

            Console.Write("DynamicHandler, ");
            //We can write to DB or file or anything
            string name = input.MethodBase.Name;
            Type objType = input.MethodBase.DeclaringType;

            IMethodReturn result = getNext()(input, getNext);

            //Console.Write("By Dynamic Handler ");
            //We can write to DB or file or anything

            return result;
        }

    }



Code to create Objects:
public static TInterface GetFactory() where TObject : TInterface
        {
            container.AddNewExtension();
            container.RegisterType().Configure().SetInterceptorFor(
                new InterfaceInterceptor());
            container.Configure().AddPolicy("Test").AddMatchingRule(new MethodMatchingRule("Write")).AddCallHandler(new DynamicHandler());
            var logger = container.Resolve();
            return (TInterface)logger;
        }



Code to execute:
            ILogger logger = InterfaceInterceptorProxy.GetFactory<ILogger, Logger>();
            logger.Write("World.");

Thursday, September 17, 2009

Policy Injection and Unity Application block

This sample will help you understand how policy injection and Unity Application blocks can be used together to achieve Auditing.
One can leverage the matching rules shipped with Policy Injection block along with the custom Handlers option in Unity Application Block.

To be able to create Custom Handlers, one has to Implement the ICallHandler interface available in "Microsoft.Practices.Unity.InterceptionExtension"


Example:

















The ICallHandler interface has an method "Invoke" which needs to be overriden. In that method, we can write code before executing an particular method and after also.

IMethodReturn result = getNext()(input, getNext); indicates the actual execution of method. Whatever code written before this statement will be executed before the actual method call. And whatever code written after this statement will be executed after the actual method call.

And the application configuration file has to be updated with something like this;