How to intercept methods.

Topics: Exception Handling Application Block, Logging Application Block, Policy Injection Application Block
May 24, 2011 at 5:32 AM

HI,

I am trying to setup interception for exception handling and logging for my types configured. Please see my config. Exception handling and logging are removed for bravity.

<policyInjection>
    <policies>
      <add name="DataBaseExceptionsPolicy">
        <matchingRules>
          <add type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.NamespaceMatchingRule, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              name="Namespace Matching Rule">
            <matches>
              <add match="Test" />
            </matches>
          </add>
        </matchingRules>
        <handlers>
          <add type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.PolicyInjection.ExceptionCallHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              exceptionPolicyName="DataExceptionPolicy" name="Exception Handling Call Handler" />
        </handlers>
      </add>
    </policies>
  </policyInjection>


  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"></sectionExtension>
    <container>
      <extension type="Interception"/>
      
    </container>
  </unity>

and then I have below code

  public class Unity
    {
        private const string unity = "unity";
        /// <summary>
        /// Initializes the Unity Application block.
        /// </summary>
        static Unity()
        {
            try
            {

                IUnityContainer container = new UnityContainer();
                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(unity);
                if (null != section)
                {
                    section.Configure(container);
                }

                container.AddNewExtension<EnterpriseLibraryCoreExtension>();
                container.AddNewExtension<Interception>();
                container.AddNewExtension<UnityServicesExtension>();
                
                
                IConfigurationSource configSource = ConfigurationSourceFactory.Create();
                PolicyInjectionSettings settings = (PolicyInjectionSettings)configSource.GetSection(PolicyInjectionSettings.SectionName);
                if (settings != null)
                {
                    settings.ConfigureContainer(container, configSource);
                }

		  //removed code fopr bravity.
                    Type i= Type.GetType("some interafce ");
                    Type c= Type.GetType("class implementation");
                    this.Container.RegisterType(i, c);

                    this.Container.Configure<Interception>().SetDefaultInterceptorFor(i, new InterfaceInterceptor());


                Unity.Default = container;


            }
            catch (Exception ex)
            {
                throw new ConfigurationException(string.Format("Unity application block is not initialized.Please verify web.config file.Error {0}", ex.Message));
            }
        }

now when  I call resolve and call a method, if that method throws an exception , I excepet that to be logged using logging application block. I am not sure what I am doing wrong here.

Please help.

May 24, 2011 at 4:09 PM

Hi,

We'll get back to you on this one since we're not yet able to look closely at the code you posted.

Though is there any chance you have already read using Enterprise Library Call Handlers section in Unity documentation which does provide interception with Entlib's App block such as logging, exception handling and etc. Hope this helps.

Gino Terrado
Global Technologies and Solutions

Avanade, Inc.

entlib.support@avanade.com
May 24, 2011 at 5:53 PM

Hi,

Thank you. My requirement is , The types (interface and class) will be configured in a seperate section in .config file, It is not under unity section. 

I would like to register the types with unity and setup interception for exception handling and logging . I am using entlib 5.* and unity 2.0

Please help me to do this.

May 25, 2011 at 4:52 PM

Hi,

Can you drop us an email so we can provide a sample for this that I think would be helpful.

Gino Terrado
Global Technologies and Solutions

Avanade, Inc.

entlib.support@avanade.com
May 27, 2011 at 2:36 PM

Hi,

The below solution will not work for us. we have a seperate configuration section to configure the types as shown below. I want to register the types when unity is initialized and setup interception. Please help me on this.

<MyConfig>

<Service Contract="IAccountService,AccountService,version=1.0.0.0,culture.............."        Implementation="AccountService,AccountService,version=1.0.0.0,culture.............."/>
<BusinessObject Type="AccountBusinessObjects.AccountBO,AccountBusinessObjects, version=1.0.0 .........."/>
 <DataaccessObjects Interface="IAccountDAO,AccountsDataAccess"  default="real">
<Implementation name="real" Type="AccountDAO,AccountsDataAccess,version..."/>
<Implementation name="stub" type="AccountDAOSTUB,AccountsDataAccess,version...."/> </DataaccessObjects> </MyConfig>  

 

Your email:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
    <container>
      <extension type="Interception" />
      <register type="PIABWithUnity.IDummyService, PIABWithUnity" mapTo="PIABWithUnity.DummyService, PIABWithUnity">
        <interceptionBehavior type="PolicyInjectionBehavior"/>
        <interceptor type="InterfaceInterceptor"/>
      </register>
    </container>
  </unity>

 

Code:

 

        static IUnityContainer ConfigurePolicyInjectionWithUnity()
        {

            IUnityContainer container = new UnityContainer();

           
            container.AddNewExtension<EnterpriseLibraryCoreExtension>()
                     .AddNewExtension<Interception>();

 

            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Configure(container);
 
            return container;
        }

 

 

May 27, 2011 at 7:46 PM

You will need to write the code that reads your custom configuration section and calls the Unity APIs to set up the registrations. There's no way around that if you're not using the existing configuration schema.

 

May 28, 2011 at 12:31 PM

Hi,

What code I should write to call Unity API? Can you please give me a sample?

Type interfaceType=read from configuration section

Type classType= read from configuration section

Now how do register with unity and setup interception?

Please help me.

Thanks

Hari

May 30, 2011 at 3:43 AM
Edited May 30, 2011 at 3:46 AM

Hi,

As what Chris Tavares just said, you need to write a code that reads your custom config section and then supply the fetched value to the GetType method. You can do something like this:

            IUnityContainer container = new UnityContainer();
            Type myInterface = Type.GetType("Test.IMyType, UnityTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
            Type myClass = Type.GetType("Test.MyType, UnityTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
            container.RegisterType(myInterface, myClass, new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>());
            var myobj = container.Resolve(myClass);
Take note that you should have already added reference to the assemblies you've defined on your custom config for this to work. Also note that since you use the implicit resolve, you cannot directly call the methods of the resolved instance. You need reflection to do that. Hope it helps :)
 
Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com