Unity handles IOC AOP

Source: Internet
Author: User
Tags throw exception

With unity you can do the IOC (inversion of Control) AOP (tangent) can do uniform exception and log processing, It is very convenient, the project is implemented with Microsoft.Practices.Unity in Microsoft Enterprise Library


1 defining interfaces and implementations

    //Defining Interfaces     public InterfaceIproductservice {stringgetproduct (); }    //implementing Interfaces     public classProductservice:iproductservice { public stringgetproduct () {inti =0; intj =1; //Throw Exception            return(j/i).        ToString (); }    }

2 Implementing Dependency Inversion

  public Sealed classServicelocator:iserviceprovider {#regionPrivate fieldsPrivate ReadOnlyIunitycontainer container; #endregion        #regionPrivate Static FieldsPrivate Static ReadOnlyServicelocator instance =NewServicelocator (); #endregion        #regionCtor/// <summary>        ///Initializes a new instance of<c>Servicelocator</c>class. /// </summary>        Privateservicelocator () {unityconfigurationsection section= (unityconfigurationsection) Configurationmanager.getsection ("Unity"); Container=NewUnityContainer (); Section.        Configure (container); }        #endregion        #regionPublic Static Properties/// <summary>        ///Gets The Singleton instance of the<c>Servicelocator</c>class. /// </summary>         public Staticservicelocator Instance {Get{returninstance;} }        #endregion        #regionPrivate MethodsPrivateIenumerable<parameteroverride> Getparameteroverrides (ObjectOverridedarguments) {List<ParameterOverride> overrides =NewList<parameteroverride>(); Type Argumentstype=Overridedarguments.gettype (); Argumentstype.getproperties (bindingflags.public|bindingflags.instance). ToList (). ForEach ( property=                {                    varPropertyValue = Property. GetValue (overridedarguments,NULL); varPropertyName =property .                    Name; Overrides. ADD (Newparameteroverride (propertyname, propertyvalue));            }); returnoverrides; }        #endregion        #regionPublic Methods/// <summary>        ///Gets The service instance with the given Type. /// </summary>        /// <typeparam name= "T" >The type of the service.</typeparam>        /// <returns>the Service Instance.</returns>         publicT getservice<t>()        {            returnContainer. Resolve<t>(); }        /// <summary>        ///Gets The service instance with the given type by using the overrided Arguments. /// </summary>        /// <typeparam name= "T" >The type of the service.</typeparam>        /// <param name= "overridedarguments" >the overrided Arguments.</param>        /// <returns>the Service Instance.</returns>         publicT getservice<t> (ObjectOverridedarguments) {            varoverrides =Getparameteroverrides (overridedarguments); returnContainer. Resolve<t>(overrides.        ToArray ()); }        /// <summary>        ///Gets The service instance with the given type by using the overrided Arguments. /// </summary>        /// <param name= "servicetype" >The type of the service.</param>        /// <param name= "overridedarguments" >the overrided Arguments.</param>        /// <returns>the Service Instance.</returns>         public ObjectGetService (Type servicetype,ObjectOverridedarguments) {            varoverrides =Getparameteroverrides (overridedarguments); returnContainer. Resolve (servicetype, Overrides.        ToArray ()); }        #endregion        #regionIServiceProvider Members/// <summary>        ///Gets The service instance with the given Type. /// </summary>        /// <param name= "servicetype" >The type of the service.</param>        /// <returns>the Service Instance.</returns>         public ObjectGetService (Type Servicetype) {returnContainer.        Resolve (servicetype); }        #endregion    }
View Code

3 Exception Blocking class

 public classExceptionloggingbehavior:iinterceptionbehavior { publicIenumerable<type>getrequiredinterfaces () {returntype.emptytypes; }         publicimethodreturn Invoke (imethodinvocation input, getnextinterceptionbehaviordelegate GetNext) {varMethodreturn =GetNext ().            Invoke (input, getNext); if(methodreturn.exception! =NULL) {console.writeline ("Intercept to Exception"+methodReturn.Exception.Message); }            returnmethodreturn; }         public BOOLWillExecute {Get{return true; } }    }

4 App. Config configuration

<?XML version= "1.0" encoding= "utf-8"?><Configuration>  <configsections>    < sectionname= "unity"type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration "/>  </configsections>    <Startup>         <supportedruntimeversion= "v4.0"SKU=". netframework,version=v4.5.2 " />    </Startup>  <!--begin:unity -  <Unityxmlns= "http://schemas.microsoft.com/practices/2010/unity">    <sectionextensiontype= "Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration "/>    <Container>      <extensiontype= "interception"/>      <!--Cache Provider -      <Registertype= "unityaop.iproductservice, unityaop"Mapto= "unityaop.productservice, unityaop">        <Interceptortype= "interfaceinterceptor"/>        <!--<interceptionbehavior type= "unityaop.cachingbehavior, unityaop"/> -        <Interceptionbehaviortype= "unityaop.exceptionloggingbehavior, unityaop"/>      </Register>    </Container>  </Unity>  <!--end:unity -</Configuration>

5 Calls

Static void Main (string[] Args)        {            =  servicelocator.instance.getservice<iproductservice> ();             Try             {                Service. GetProduct ();            }             Catch (Exception Ex)            {            }            console.read ();        }

A simple example

Code:Http://files.cnblogs.com/files/zery/UnityAOP.rar

Unity handles IOC AOP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.