Simple application of Unity IOC container

Source: Internet
Author: User
Tags aliases

Transferred from: http://blog.csdn.net/wanzhuan2010/article/details/7763280

Unity is a lightweight, extensible, dependency injection container implemented by the Microsoft patterns& Practices group in C # that facilitates the development of loosely coupled applications for developers.

Has the following advantages:

1. Simplifies the creation of objects, especially for hierarchical object structures and dependencies;

2. Abstraction of requirements, allowing developers to specify dependencies in runtime or configuration files, simplifying management of crosscutting concerns;

3. Delays in configuring components for containers adds flexibility;

4. Service positioning capability, which enables customers to store or cache containers;

5. Instance and type interception

: http://unity.codeplex.com/

The latest version is the Unity 3.0 for. NET 3.5 Preview

The following program is in version 2.1

Start the Unity tour below

(a) My first unity Demo

Create a new console application that references the Microsoft.Practices.Unity.dll file;

Create a new bird interface that defines a method of bird barking;

[CSharp]View Plaincopy
    1. <summary>
    2. Bird interface
    3. </summary>
    4. Public Interface Ibird
    5. {
    6. // <summary>
    7. /// speech
    8. // </summary>
    9. void Say ();
    10. }

To implement this interface:

[CSharp]View Plaincopy
    1. <summary>
    2. Swallow
    3. </summary>
    4. Public class Swallow:ibird
    5. {
    6. public void Say ()
    7. {
    8. Console.WriteLine ("The Swallow is barking ...");
    9. }
    10. }


Implement IOC inversion control through unity in the Mian method;

[CSharp]View Plaincopy
  1. static void Main ( string[] args)
  2. {
  3. //instantiation of a controller
  4. Iunitycontainer UnityContainer = new UnityContainer ();
  5. //Implementation injection
  6. Unitycontainer.registertype<ibird, swallow> ();
  7. Ibird bird = unitycontainer.resolve<ibird> ();
  8. Bird. Say ();
  9. Console.read ();

Operation Result:

This small instance has implemented a simple IOC inversion of control.

What if there are two implementations of an interface? Is it possible to add a code similar to the one below? Try it below.

Unitycontainer.registertype<ibird, swallow> (); We add a sparrow class to the original program to implement the Ibird interface:

[CSharp]View Plaincopy
    1. Public class Sparrow:ibird
    2. {
    3. public void Say ()
    4. {
    5. Console.WriteLine ("Sparrow is calling ....");
    6. }
    7. }


Main Method Code:

[CSharp]View Plaincopy
    1. Instantiate a controller
    2. Iunitycontainer UnityContainer = new UnityContainer ();
    3. Implementation injection
    4. Unitycontainer.registertype<ibird, swallow> ();
    5. Unitycontainer.registertype<ibird, sparrow> ();
    6. Ibird bird = unitycontainer.resolve<ibird> ();
    7. Bird. Say ();
    8. Console.read ();

Run it and the result:

Well, what's the situation, and why is the sparrow barking? Instead of the Swallow's bark? Originally

When an interface has multiple implementations and is not distinguished by aliases, the last injected implementation is chosen;

Add aliases to each injection below:

[CSharp]View Plaincopy
  1. Instantiate a controller
  2. Iunitycontainer UnityContainer = new UnityContainer ();
  3. Implementing injection, using aliases to differentiate between implementations
  4. Unitycontainer.registertype<ibird, swallow> ("Swallow");
  5. Unitycontainer.registertype<ibird, sparrow> ("Sparrow");
  6. Ibird swallow = unitycontainer.resolve<ibird> ("Swallow");
  7. Ibird Sparrow = unitycontainer.resolve<ibird> ("Sparrow");
  8. Swallow. Say ();
  9. Sparrow. Say ();
  10. Console.read ();


Operation Result:

This is the result we want, haha .....

When an interface has multiple implementations, it needs to be distinguished by an alias.

(ii) Unity's constructor injection

Create a new Ibirdhome interface and implement the interface:

[CSharp]View Plaincopy
  1. <summary>
  2. The home of the bird
  3. </summary>
  4. Public Interface Ibirdhome
  5. {
  6. Ibird Swallow { get;  set;}
  7. }
  8. <summary>
  9. The home of the bird
  10. </summary>
  11. Public class Birdhome:ibirdhome
  12. {
  13. Public Ibird Swallow { get;  set;}
  14. Public birdhome (ibird bird)
  15. {
  16. This .  Swallow = bird;
  17. }
  18. }

The main method is as follows:

[CSharp]View Plaincopy
    1. Instantiate a controller
    2. Iunitycontainer UnityContainer = new UnityContainer ();
    3. Implementation injection
    4. Unitycontainer.registertype<ibird, swallow> ();
    5. Unitycontainer.registertype<ibirdhome, birdhome> ();
    6. Ibirdhome birdhome = unitycontainer.resolve<ibirdhome> ();
    7. BirdHome.Swallow.Say ();
    8. Console.read ();

Operation Result:



We just got a ibirdhome implementation through unity, but we didn't instantiate the Ibird swallow {get; set;}, but the results have been run and there are no errors.

It turns out that unity has helped us do this and we can steal a lazy one. Hey ...

(iii) attribute injection

Remove the middle constructor of the Birdhome class and add the [Dependency] attribute to the attribute

[CSharp]View Plaincopy
  1. <summary>
  2. The home of the bird
  3. </summary>
  4. Public class Birdhome:ibirdhome
  5. {
  6. // <summary>
  7. /// attribute injection
  8. // </summary>
  9. [Dependency]
  10. Public Ibird Swallow { get;  set;}
  11. }

The result is the same as the result, pro, don't believe, try!

(iv) Initial injection of the device (name from which it originated)

The initial renderer injection is similar to the constructor injection, but does not need to be written into the constructor, but instead adds the [Injectionmethod] feature to the initial method of the initialization.

[CSharp]View Plaincopy
  1. // <summary>
  2. /// initializer injection
  3. // </summary>
  4. /// <param name= "Bird" ></param>
  5. [Injectionmethod]
  6. public void Initialize (ibird bird)
  7. {
  8. This .  Swallow = bird;
  9. }

The result of the operation remains:

Welcome everyone to come and shoot bricks ...!

Life is endless, programming not only!

Simple application of Unity IOC container (RPM)

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.