Without the Unity Library, implement it yourself. NET Lightweight Dependency Injection

Source: Internet
Author: User
Tags in domain

In object-oriented design, Dependency injection (IoC), as an important design pattern, is mainly used to reduce the coupling problem of computer programs, compared to the spring framework in Java, The Unity framework in the Microsoft Enterprise Library is one of the more widely used dependency injection frameworks in the current. NET platform (and some spring.net, etc.). But for these "official versions" of the strong Dependency injection framework, which is often more complex to use and configure, I personally prefer to implement a "convention better than the configuration" lightweight IOC framework.

The implementation of dependency injection is mainly the use of the Reflection technology in C #, through the configuration file, the implementation of the code to inject into the interface. The user just accesses the interface, for the implementation of the interface is not known, can effectively decouple the interface and implementation, before introducing the code, first look at our configuration file:

 <  appsettings  >  <!--  Dependency injection configuration  -->  <  add  key  = "Domain.Entity.IRepository"   = "Infrastructure.repository"  /  </ appsettings  >  

Both Domain.Entity.IRepository and infrastructure.repository are assemblies (DLLs) in. NET, where the warehousing interfaces required in the domain model are defined in Domain.Entity.IRepository, infrastr Ucture. The implementation of the warehousing interface is defined in the repository. Domain models need access to data, not directly to ADO or ORM, Instead, by accessing the warehousing interface in the Domain.Entity.IRepository and injecting the implementation of the infrastructure.repository into the interface through dependency injection, it effectively isolates the domain model's reliance on data implementations, and if the database or ORM framework needs to be replaced later, Just implement another infrastructure.repository and update the dependency injection configuration.
The following describes the implementation of lightweight dependency injection, which is preceded by code:  

     Public Sealed classDependencyinjector {/// <summary>        ///load the corresponding class according to the name and parameters of the constructor/// </summary>        /// <typeparam name= "T" >interfaces implemented by classes that need to be loaded</typeparam>        /// <param name= "ClassName" >the name of the class</param>        /// <param name= "args" >parameters of the constructor (default is null)</param>        /// <returns>interface of the class</returns>         Public StaticT getclass<t> (stringClassName,Object[] args =NULL)whereR |class        {            //gets the namespace in which the interface resides            stringFactoryname =typeof(T).            Namespace; //obtaining the namespace of an interface implementation through a dependency injection configuration file            stringDllName =Configurationmanager.appsettings[factoryname]; //gets the full name of the class            stringFullClassName = DllName +"."+ClassName; //use reflection to load classes based on DLL and class name            ObjectClassobject = Assembly.Load (dllName). CreateInstance (FullClassName,true, Bindingflags.default,NULL, args,NULL,NULL); ; returnClassobject asT; }    }

the typeof (T) in the code. Namespace, where T is the type of interface, gets the namespace of the interface, and then through our configuration file, you can get the namespace of the class, plus the class name, through the reflection mechanism of C #, you can load the implementation of the class. Perhaps you would say that we only know the interface, do not know what the class name is, don't worry, we will further encapsulate the code:

 Public Sealed classIoC {/// <summary>        /////implemented by interface name and constructor parameters/// </summary>        /// <typeparam name= "T" >interface Type</typeparam>        /// <param name= "args" >parameters of the constructor function</param>        /// <returns>implementation of the interface</returns>         Public StaticT resolve<t> (Object[] args =NULL)whereT:class        {            //Get class name            stringClassName =typeof(T). Name.substring (1); //Determine If the FullName is generic by judging whether it contains ' symbols '            stringFullName =typeof(T).            FullName; intFlag = Fullname.indexof ('`'); //if it is generic, special handling is required            if(Flag! =-1)            {                intDot = Fullname.lastindexof ('.', flag); //this removes the dot in front of the method name and IClassName = fullname.substring (dot +2); }            returnDependencyinjector.getclass<t>(ClassName, args); }    }

Here we use the above-mentioned "convention is better than configuration", we agree that the name of the interface is preceded by the class name and I, and the interface and implementation must be a separate assembly. If the class name is helper, then the name of the interface must be ihelper, and we get the implemented class name by removing the I from the front of the interface. In the case of generic interfaces, special processing is also required, where we determine whether a generic interface is determined by determining whether the full name of the type contains the "'" symbol.

Here is an example of using this dependency injection:

 Public Static Book GetById (string  BookID)        {            irepository<Book> bookrep = ioc.resolve< Irepository<book>>();             return Bookrep.getbykeys (BookID);        }          Public int Getbookcount ()        {            = ioc.resolve<ibookrepository>();             return Bookrep.getcount ();        }

Here we do not know the implementation of the interface, through our encapsulated Ioc.resolve method, we can put the interface in our configuration file "injected into the interface", through this decoupling way, later I can more flexibility to refactor the code.

The

does not use the Unity Library for its own implementation. NET lightweight Dependency Injection

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.