Unity Container application example: unitycontainer

Source: Internet
Author: User

Unity Container application example: unitycontainer
1. Reference Unity

Right-click the project reference and choose manage Nuget package> search for unity> install Unity and Unity Interception Extension, as shown in.

2. Create a basic class

Take the data layer injection for commodity query as an example.

1. First create the commodity entity Model. If the commodity information is to be serialized, you must add the Serializable feature for this class.

public class Product    {        public int Id { get; set; }        public string Name { get; set; }        public int Price { get; set; }        public override string ToString()        {            return string.Format(" Product id:{0}\r\n Name:{1}\r\n Price:{2}\r\n",Id,Name,Price);        }    }

2. Create a data layer interface and its implementation class.

public interface IProductDao    {        Product Get(int id);    }
public class ProductDao:IProductDao    {        public Product Get(int id)        {            #warning product info for test            return new Product()            {                Id = id,                Name = "Product"+id,                Price = id*10            };        }    }

3. directly create an instance

In fact, with the above content, you can call to query the product information.

static void Main( string[] args)         { IProductDao productDao= new ProductDao(); Product product = productDao.Get(5); Console.WriteLine(product.ToString()); Console.Read();         }

Iii. Use Unity for 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"> <! -- Assembly and namespace --> <assembly name = "DemoCache"/> <namespace name = "DemoCache. dao "/> <namespace name =" DemoCache. dao. impl "/> <container name =" Dao "> <! -- Product --> <register type = "IProductDao" mapTo = "ProductDao"> </register> </container> </unity> </configuration>

2. Create the UnityContainerManager class

Create UnityContainerManager to read the Unity. config configuration. For the complete code, see the attachment. Focus on how to read the configuration information from Unity. config:

Private IUnityContainer LoadUnityConfig () {// obtain the specified config file string filePath = AppDomain Based on the file name. currentDomain. baseDirectory + @ "Configs \ Unity. config "; var fileMap = new ExeConfigurationFileMap {ExeConfigFilename = filePath}; // read Configuration information from the config file configuration Configuration = ConfigurationManager. openMappedExeConfiguration (fileMap, ConfigurationUserLevel. none); var unitySection = (UnityConfigurationSection) configuration. getSection ("unity"); var container = new UnityContainer (); foreach (var item in unitySection. containers) {container. loadConfiguration (unitySection, item. name);} return container ;}

3. Call example

static void Main( string[] args)         { IProductDao productDao = UnityContainerManager .Instance.Resolve<IProductDao >(); Product product = productDao.Get(8); Console.WriteLine(product.ToString()); Console.Read();         }
4. Use Unity Interception to implement logs

1. Create an ICallHandler interface implementation class

Create a LogCallHandler class to implement the ICallHandler interface. The execution time is automatically written into the log every time the corresponding method is called.

Public class LogCallHandler: ICallHandler {public IMethodReturn Invoke (IMethodInvocation input, GetNextHandlerDelegate getNext) {// time start var stopWatch = new Stopwatch (); stopWatch. start (); // execution method IMethodReturn result = getNext () (input, getNext); // The timer ends stopWatch. stop (); // record the log var argumentsSb = new StringBuilder (input. methodBase. name); for (var I = 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); return result;} public int Order {get; set;} public string Msg {get; set ;}}

2. Create features

Create the LogTime feature. It must implement HandlerAttribute.

public class LogTimeAttributes:HandlerAttribute    {        public int Order { get; set; }        public string Msg { get; set; }        public override ICallHandler CreateHandler(IUnityContainer container)        {            return new LogCallHandler()            {                Order = Order,                Msg = Msg            };        }    }

3. Usage features

[LogTimeAttributes (Order = 1, Msg = "querying single item information")]

4. Configure Unity. config

To configure Unity Interception, you must add it under the unity node:

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

Then add the following under the container node:

< extension type= "Interception " />

Finally, adjust the registration node of IProductDao:

< register type= "IProductDao " mapTo= "ProductDao ">         < interceptor type =" InterfaceInterceptor" />         < policyInjection /> </ register>

No adjustment is required for the call. The result is as follows:

Static void Main (string [] args) {var 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

Related Article

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.