. A brief introduction to implementing extensible programming methods under net

Source: Internet
Author: User

The

IOC controlled inversion (inversion of control, English abbreviation for IOC) is an important object-oriented programming law used to solve system coupling problems. Control inversion There is also a name called Dependency injection (di:dependency injection). The most basic technology in the IOC is interface + reflection, "Reflection (reflection)" programming. "The role of the IoC container is the creation of objects, the core of which is the life cycle management of objects (when to create/how to create/when to destroy), like a large factory where objects are" managed "inside. The source of the pattern is SOLID (object-oriented principle). The core of the use of IOC decoupling is: for abstraction, not for implementation. That is, we just need to focus on what an object can do, how to use it, not to focus on how it comes, not to manage it.
1,unity  
Unity is a lightweight, extensible dependency injection container that Enterprise Library 4.0 is starting to join. The
Unity module includes the following features  
• Provides a method for creating objects and dependent objects  
• The Registertype method provided is used to register types and mappings in the container, The Resolve method can return an instance of any dependent object.  
• Provides control inversion IOC functionality, implemented by pre-configuring an object that injects classes. You can specify either a class or an interface (constructor injection) in the constructor, or a property injection using attribute, and a method call injection.  
• Container inheritance is supported, containers can have child containers, and objects are passed from child containers to parent containers.  
• You can read information from a standard configuration file, such as an XML file  
• You can configure and change dependencies at run time.  
• There is no requirement for the definition of a class. There is no need to add attribute on a class (unless you use attribute injection or method call injection), there is no restriction in the class declaration.  
• Support for custom containers, for example, you can implement additional object constructs in methods, and container functions, such as the caching capabilities of containers.

Three ways to inject:
• Constructor Injection (Constructor injection): The IOC container intelligently chooses and invokes the appropriate constructors to create dependent objects. If the selected constructor has corresponding parameters, the IOC container will customize the creation of the corresponding parameter object before calling the constructor;
• Attribute injection (Property injection): If a property of the dependent object needs to be used, the IOC container will initialize the property automatically after the dependent object is created;
• Method Injection: If a dependent object needs to invoke a method for initialization, the IOC container automatically calls the method after the object is created.

Define an interface:

public interface ILogger {void Write (string message);

Implementing an interface to extend an application:

    public class Flatfilelogger:ilogger    {public        void Write (String message)        {            Console.WriteLine ( String.Format ("message:{0}", Message));            Console.WriteLine ("Target:flatfile");        }    }

Main program:

    Class program    {        static void Main (string[] args)        {            ILogger logger = GetLogger ();            Logger. Write ("Test");            System.Console.ReadLine ();        }        <summary>//        Load Log processing objects///</summary>//        <returns></returns>        public static ILogger GetLogger ()        {            //Initialize a container            iunitycontainer container = new UnityContainer ();            Get Unity configuration            unityconfigurationsection config = configurationmanager.getsection ("Unity") as unityconfigurationsection;            UnityConfigurationSection.CurrentSection.Configure (container);            Registers an object in the container            ILogger Defaultlogger = container. Resolve<ilogger> ("Logger");            return defaultlogger;        }    }

Extended configuration:

<configuration>  <configSections>    <section name= "Unity" type= " Microsoft.practices.unity.configuration.unityconfigurationsection,microsoft.practices.unity.configuration "/ >  </configSections>  <unity>    <typeAliases>      <typealias alias= " Flatfilelogger "Type=" IoCTest.Unity.FlatFileLogger, ioctest.unity "/>      <typealias alias=" ILogger "type=" IoCTest.Unity.ILogger, ioctest.unity "/>    </typeAliases>    <containers>      <container >        <types>          <type name= "Logger" type= "ILogger" mapto= "Flatfilelogger"  />        </ types>      </container>    </containers>  </unity></configuration>

2,spring.net
Spring.net is an application framework designed to assist developers in creating enterprise-class. NET Applications. It provides many aspects of functionality, such as dependency injection, aspect-oriented programming (AOP), data access abstraction, and ASP. Spring.net's IOC container solves the problem of how to synthesize applications into classes, objects, and service groups in enterprise applications. The IOC container combines the dispersed components into a complete application. The Spring.core is based on the Iobjectfactory interface, which implements the factory pattern in a simple and elegant way, allowing us to not write the singleton type and numerous service locators ourselves, and to decouple the object configuration and its dependencies from the specific program logic. The Iapplicationcontext interface in this module is an extension of the iobjectfactory, adding many enterprise-class features, including text localization using resource files, event propagation, and resource loading, among others.
Define an interface:

public interface ILogger {void Write (string message);

Implementing the interface:

    public class Filelogger:ilogger    {public        void Write (String message)        {            Console.WriteLine ( String.Format ("message:{0}", Message));            Console.WriteLine ("Target:file");        }    }

Main program:

        static void Main (string[] args)        {            //Initialize container            iapplicationcontext context = Contextregistry.getcontext ();            Gets the object in the container            ILogger Logger = context. GetObject ("Logger") as ILogger;            Logger.write ("Test");            Console.ReadLine ();        }

System configuration:

<configuration>  <configSections>    <sectiongroup name= "Spring" >      <section name= " Context "Type=" Spring.Context.Support.ContextHandler, Spring.core "/>      <section name=" Objects "type=" Spring.Context.Support.DefaultSectionHandler, Spring.core "/>    </sectionGroup>  </ configsections>  <spring>    <context>      <resource uri= "Config://spring/objects"/>    </context>    <objects xmlns= "http://www.springframework.net" >      <object id= "Logger" Type= "ioctest.spring.filelogger,ioctest.spring" >      </object>    </objects>  </ Spring></configuration>

3. MEF Combination Parts
The MEF (Managed Extensibility framework) is already built into the. NET Framework 4.0, and you just need to add a reference System.ComponentModel.Composition. is the. NET platform next to a lightweight, extensible, plug-in system architecture without configuration (Attribute Based) extensibility Management Framework, so that we can easily extend the application and have minimal impact on existing code, Developers can use these extensibility points to interact with the application as they define some extensibility points during development, and the MEF lets the application and the Extender do not have a direct dependency, which also allows the extension to be shared among multiple, extended requirements. Although Microsoft's people strongly deny that MEF is a ioc/di tool, the truth is that it can actually be implemented Ioc/di.
Extension points for extensible applications written using MEF declare an import (imported) that can be populated by an extension component (Parts), and each extension component declares an export. MEF provides a way to extend an application by "combining" the implicit discovery of parts. The so-called import is: Specify "which object needs compose" in the container, so-called export: Specify "which class can be used to compose"
Contract Interface:

public interface ILogger {void Write (string message);

Declaration Export:

    <summary>/////    which class can be used to compose, meaning that the class is not an implementation class that can be populated, so the export tag is a class, not a specific object. //    </summary>    [Export ("ILogger1", typeof (ILogger))]    public class Filelogger1:ilogger    {public        void Write (String message)        {            Console.WriteLine ( String.Format ("message:{0}", Message));            Console.WriteLine ("Target:file");        }    }

Declaration Import:

    Class Ts {///<summary>//////        -which object needs compose. That is, you need to be implemented to fill the class, so the import tag is an object, generally the object is an interface, because if it is a specific class, then still need to import it? //        </summary>        [Import ("ILogger1")]        Public ILogger Logger {get; set;}        Public Ts ()        {            var catalog = new Aggregatecatalog ();            Add the parts found in the program's assembly to the directory                     //catalog. Catalogs.add (New Assemblycatalog (typeof). Assembly));                Adds a part found from the specified path to the catalog                    . Catalogs.add (New Directorycatalog (AppDomain.CurrentDomain.BaseDirectory));            var container = new Compositioncontainer (catalog);            By calling the container's Composeparts () method, you can combine the parts in the container.             Container.composeparts (this);        }    }

Main program:

static void Main (string[] args) {TS ts = new TS (); ts. Logger.write ("Test"); System.Console.ReadLine (); }

The advantage of MEF over a framework like spring.net is that first it is built into the. NET framework, you don't have to add third-party references, you worry about updates to third-party components, and then it's free to configure, It is tempting to be free of configuration for a behemoth like Spring.net. For unity, its advantages are the same, the. NET Framework is built-in, without configuration, without the need for hard code declarations. Of course there is no direct reference, which is what all IOC do.
MEF can also automatically discover parts with metadata without acquiring parts assembly/dll. For a complete introduction to MEF, please visit msdn:http://msdn.microsoft.com/en-us/library/dd460648.aspx

. A brief introduction to implementing extensible programming methods under net

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.