C # Ioc, DI, Unity, TDD ideas and practices

Source: Internet
Author: User
Tags assert

Object-oriented design (OOD) helps us develop high-performance, easy-to-scale, and reusable programs. Among them, Ood has an important idea that is the dependency inversion principle (DIP).

dependency Inversion principle (DIP): A principle of software architecture design (abstract concept)

Inversion of Control (IoC): a way of reversing flows, dependencies, and interfaces (specific implementations of dips)

Dependency Injection (DI): An implementation of the IOC, used to reverse the dependency (the specific implementation of the IOC)

IOC container: a framework of dependency injection used to map dependencies, manage object creation and life cycle (DI framework),

Unity: A Microsoft-launched IOC framework

TDD: test-driven development, a core practice and technology in agile development, is also a design methodology

The above contents are copied (English is not good, put here for reference), related content to see some, unknown feeling li.

Once wrote a hotel reading and writing room card procedures, different hotel door locks are not the same, the same hotel may also change the door lock, program flow:

1. Get the current hotel door lock type via API

2. Download the DLL that corresponds to the latch if necessary

3. Read and Write functions

First, define the interface

Create a new Class library (Lock.interface) with the following code:

namespace lock{public interface ILock {//<summary>///        locks initialized        //</summary> <param name= "password" > Initialize password </param>        //<returns></returns>        bool Init (int password);}    }

Is it an IOC? (I'm not sure)

Second, Unit testing

Create a new unit test project (lock.tests) with the following code:

1. Latch a unit test

    /// <summary>    ///door lock a test/// </summary>[TestClass ()] Public classlockatests {/// <summary>        ///Initialize, password is a positive odd number/// </summary>[TestMethod ()] Public voidinittest () {ILock L=NewLocka (); varret = L.init (1); Assert.AreEqual (ret,true); RET= L.init (2); Assert.AreEqual (ret,false); RET= L.init (-1); Assert.AreEqual (ret,false); }    }

2. Door Lock B Unit Test

    <summary>    ///Lock B Test    ///</summary> [TestClass ()] public    class lockbtests    {        <summary>        ///initialization test, password is positive even        //</summary> [TestMethod ()] public        void Inittest ()        {            ILock L = new lockb ();            var ret = l.init (1);            Assert.AreEqual (ret, false);            ret = L.init (2);            Assert.AreEqual (ret, true);            ret = L.init ( -1);            Assert.AreEqual (ret, false);        }

Obviously the compilation does not pass (can not be compiled is also a test)

Iii. Definition of Classes

1. Create the door lock Class A library (Lock.locka) with the following code:

    <summary>///Lock A///    </summary> public    class Locka:ilock    {                //<summary>< c6/>///Initialize//</summary>//        <param name= "password" > correct password is positive odd </param>///        < returns></returns> Public        bool Init (int password)        {            return password > 0 && ( Password% 2) = = 1;        }    }

2. Create a door lock Class B library (LOCK.LOCKB) with the following code:

    <summary>///    door lock b///    </summary> public    class Lockb:ilock {//        <summary >//Initialize///</summary>//        <param name= "password" > correct password is positive even </param>//        <returns></returns> Public        bool Init (int password)        {            return password > 0 && ( Password% 2) = = 0;        }    }

After compiling successfully, go back to the test project, add the reference, compile the pass, run the test:

Not TDD?

Iv. Main Program

1. Adding the console project

2. Add Unity (5.8.6) package

3. Modify the app. config to:

<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <section name= "Unity" ty Pe= "Microsoft.practices.unity.configuration.unityconfigurationsection,unity.configuration, Version=5.2.1.0, Culture=neutral, publickeytoken=6d32ff45e0ccc69f "/><!--Some of the content on the web copied over with errors, and later viewed the definition of unityconfigurationsection, copied the corresponding assembly type= "namespace. Class name, assembly" -</configSections> <unity> <containers> <container name= "Locka" > <register type= "Lock.ilock,lock.interface" mapto= "Lock.locka,lock.locka" ></register> </container> <containe R name= "lockb" > <register type= "lock.ilock,lock.interface" mapto= "lock.lockb,lock.lockb" ></register&gt      ; </container> </containers> </unity> <startup> <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5.2 "/> </startup></configuration>

4. Reference interface

The 5.Main method is as follows:

        static void Main (string[] args)        {            var container = new UnityContainer ();            unityconfigurationsection config = (unityconfigurationsection) configurationmanager.getsection ( Unityconfigurationsection.sectionname);            "Locka");
ILock L = container. Resolve<ilock> (); Console.WriteLine (L.init (2)); Console.WriteLine (L.init (1)); Console.WriteLine (L.init (-1));
Console.readkey (); }

6. Copy the DLL for lock A to the running directory

7. The result of the operation is: false, True, false, is the result of door lock a

8. Change "Locka" to "lockb" and copy the DLL of door lock B to the running directory, and the result of operation is true, false, and false is the result of latch B.

It's Di, isn't it? We've all used unity.

At this point, the basic realization of the desired function, the future of the new hotel to increase the door lock C, door lock D is no problem, only the old hotel changed to lock e problem is not solved (estimate can be dynamically modified config file implementation, do not know there is no better way).

C # Ioc, DI, Unity, TDD ideas and practices

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.