Unity Container Application Example

Source: Internet
Author: User

a project referencing unity

Right-click Project References, manage NuGet packages, search unity-> install unity and unity interception Extension as shown in.

two creating the base class

We take the data layer injection of commodity query as an example.

1. First create the commodity entity model. If the commodity information is to be serialized, add the serializable attribute to the class.

 Public classProduct { Public intId {Get;Set; }  Public stringName {Get;Set; }  Public intPrice {Get;Set; }  Public Override stringToString () {return string. Format ("Product id:{0}\r\n name:{1}\r\n price:{2}\r\n", Id,name,price); }    }

2. Create the data-tier interface and its implementation class.

 Public Interface Iproductdao    {        Product Get (int  ID);    }
 Public class Productdao:iproductdao    {        public product Get (int  ID)        {            #warning the product info for test<
   
     c11/>
    return
    new 
     Product ()            {                =
     ID,                
    " 
     Product
    "+
    ID,                = id*
    }
                ;}    }
   

3. Create an instance directly

In fact, with the above content can be called to query the product information.

Static void string [] args)         {Iproductdao Productdao New  = Productdao.get (5); Console.WriteLine (product. ToString ()); Console.read ();         }

However, the coupling ratio is higher in this way in the project. Once you want to change the way Iproductdao is implemented, there are too many places to go. Using unity to implement dependency injection can reduce coupling.

Three. Using unity to implement dependency injection

1. Create a Unity configuration file

<? XML version="1.0"?> < configuration> < configsections> <!--Unity Assembly--< section name="Unity"Type ="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration "/> </configsections> < Unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <!--Assemblies and namespaces--< Assembly name="Democache"/> <namespaceName="Democache.dao"/> <namespaceName="DemoCache.Dao.Impl"/> < container name="Dao"> <!--Products--< register type="Iproductdao"mapto="Productdao"></register> </container> </unity> </configuration>

2. Create a Unitycontainermanager class

Create Unitycontainermanager read Unity.config configuration. The complete code is attached, focusing on the method of reading the configuration information from the Unity.config:

PrivateIunitycontainer Loadunityconfig () {////Get the specified config file according to the file name            stringFilePath = AppDomain.CurrentDomain.BaseDirectory +@"Configs\unity.config"; varFilemap =NewExeconfigurationfilemap {execonfigfilename =FilePath}; //reading configuration information from the config fileConfiguration Configuration =configurationmanager.openmappedexeconfiguration (Filemap, Configurationuserlevel.none); varUnitysection = (unityconfigurationsection) configuration. GetSection ("Unity"); varcontainer =NewUnityContainer (); foreach(varIteminchunitysection.containers) {container. Loadconfiguration (Unitysection, item.            Name); }            returncontainer; }

3. Invoking the sample

Static void string [] args)          = Unitycontainermanager. Instance.resolve<iproductdao >= productdao.get (8); Console.WriteLine (product. ToString ()); Console.read ();         }
four implementation logs using unity interception

1. Creating the Icallhandler Interface implementation class

Create a new class Logcallhandler class to Implement Interface Icallhandler. The execution time is automatically written to the log each time the corresponding method is called.

 Public classLogcallhandler:icallhandler { PublicImethodreturn Invoke (imethodinvocation input, getnexthandlerdelegate getNext) {//Timing Starts            varStopWatch =NewStopwatch ();            Stopwatch.start (); //Execution MethodImethodreturn result =getNext () (input, getNext); //End of timingStopwatch.stop (); //Record Log            varARGUMENTSSB =NewStringBuilder (input.            Methodbase.name);  for(vari =0; I < input. Arguments.count; i++) {Argumentssb.appendformat ("-{0}:{1}", input. Arguments.parametername (i), input.            Arguments[i]); } loghelper.loginfo (string. Format ("{2} method {0}, execution time {1} ms", ARGUMENTSSB, stopwatch.elapsedmilliseconds,msg)); returnresult; }         Public intOrder {Get;Set; }  Public stringMSG {Get;Set; } }

2. Create an attribute

Create an attribute logtime, which needs to implement Handlerattribute.

 Public classLogtimeattributes:handlerattribute { Public intOrder {Get;Set; }  Public stringMSG {Get;Set; }  Public Overrideicallhandler Createhandler (Iunitycontainer container) {return NewLogcallhandler () {Order=Order, MSG=MSG}; }    }

3. Using features

1 " Querying individual product information " )]

4. Configure Unity.config

Configuring unity interception needs to be added under the Unity node:

<
= "Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration ">
</>

Then add it under the container node:

<type= "interception"/>

Finally, adjust the Iproductdao registry node:

<type= "Iproductdao"  mapto= "Productdao">         < = " interfaceinterceptor"/></            ></  register>

There is no adjustment at the call, the result is as follows:

5. Do not use the Unity.config configuration file

In fact, you can set it directly in your code if you do not go to the Unity.config configuration file.

 static  void  Main (string  [] args) { var< /span> container = new  UnityContainer (). Addnewextension<interception> ().            Registertype<iproductdao, Productdao> (); Container. Configure  <Interception> (). Setinterceptorfor<iproductdao> (new              Interfaceinterceptor ()); Iproductdao Productdao  = container.            Resolve<iproductdao> ();            Product Product  = Productdao.get (8  );            Console.WriteLine (product);        Console.read (); }

Code: Http://files.cnblogs.com/files/janes/DemoCache.zip

Unity Container Application Example

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.