Using. NET Core to make unified dependency injection on classes in an assembly

Source: Internet
Author: User

1. Create attributes for labeling Dependency Injection

usingMicrosoft.Extensions.DependencyInjection;usingSystem;usingSystem.Collections.Generic;namespaceutil.attributes{/// <summary>    ///The class to which you want to use Di is labeled by this property to be registered in the Dependency injection container and you can specify the interface or class to be mapped by the class///This property can only be applied to classes, and this property cannot inherit/// </summary>[AttributeUsage (attributetargets.class,inherited =false)]     Public classUsediattribute:attribute {//targets is used to indicate which interfaces or classes are to be injected with dependency by the class that is decorated by the property.         PublicList<type> targettypes=NewList<type>();  Publicservicelifetime Lifetime;  PublicUsediattribute (Servicelifetime Arglifetime,paramstype[] argtargets) {Lifetime=Arglifetime; foreach(varArgtargetinchargtargets)            {Targettypes.add (argtarget); }        }         PublicList<type>gettargettypes () {returntargettypes; }         Publicservicelifetime Lifetime {Get            {                return  This. Lifetime; }        }    }}

2. Marking the classes to be injected in the assembly

usingMicrosoft.entityframeworkcore;usingMicrosoft.Extensions.DependencyInjection;usingSystem.Linq;usingSystem.Threading.Tasks;usingUser.domain;usingUser.Domain.POCOModels;usingutil.attributes;namespaceDDD. repositories.userrepositories{[Usedi (servicelifetime.scoped,typeof(iloginrepository))]  Public classLoginefcorerepository:iloginrepository {Private ReadOnlyDbContext DbContext;  Publicloginefcorerepository (DbContext DbContext) { This. DbContext =DbContext; }

3. Extend a method for iservicecollection to enable operation of the Assembly

usingMicrosoft.Extensions.DependencyInjection;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection;usingutil.attributes;namespaceutil.diplugin{ Public Static classNetcoredimoduleregister {/// <summary>        ///Automatic Registration Service/// </summary>        /// <param name= "Services" >register a collection of services (to which you register)</param>        /// <param name= "Implementationtype" >the type to register</param>         Public Static voidAutoregisterservice ( Thisiservicecollection Services, Type Implementationtype) {            //gets the object that corresponds to the Usediattribute property of the typeUsediattribute attr = Implementationtype.getcustomattribute (typeof(Usediattribute)) asUsediattribute; ////Get all interfaces implemented by the class            //type[] types = implementationtype.getinterfaces ();list<type> types =attr.            Gettargettypes (); varLifetime =attr.            Lifetime; //traversing every interface implemented by a class            foreach(varTinchtypes) {                //registering a class as an implementation of an interface-----but there is a concern that if a class implements the IDisposible interface, it is feared that the class will become an implementation of this interface .Servicedescriptor Servicedescriptor =Newservicedescriptor (t, Implementationtype, Lifetime); Services.            ADD (Servicedescriptor); }        }        /// <summary>        ///gets the collection of all types in the assembly based on the name of the assembly/// </summary>        /// <param name= "AssemblyName" >assembly name</param>        /// <returns>Type Collection</returns>         Public Statictype[] Gettypesbyassemblyname (String AssemblyName) {Assembly Assembly=Assembly.Load (AssemblyName); returnAssembly.        GetTypes (); }        #regionRegister all eligible types in an assembly to iservicecollection overload 1/// <summary>        ///All eligible types in the assembly are registered to Iservicecollection/// </summary>        /// <param name= "Services" >iservicecollection</param>        /// <param name= "Aassemblyname" >assembly name</param>         Public Static voidAutoregisterservicesfromassembly ( Thisiservicecollection Services,stringaassemblyname) {            //gets all the types in the assembly based on the name of the assemblytype[] Types =Gettypesbyassemblyname (aassemblyname); //filtering the above assembly is filtered first according to the conditions passed in and then requires that the type must be a class and cannot be an abstract classienumerable<type> _types = types. Where (t = T.isclass &&!t.isabstract); foreach(varTinch_types) {IEnumerable<Attribute> attrs =t.getcustomattributes (); //Traverse all attributes of a class                foreach(varattrinchattrs) {                    //If the attribute is found to be the Usediattribute attribute, the class is registered in the DI container.//and jump out of the current loop and start looping over the next class.                    if(attr isUsediattribute) {Services.                        Autoregisterservice (t);  Break; }                }            }        }        #endregion        #regionRegister all eligible types in an assembly to iservicecollection overload 2/// <summary>        ///All eligible types in the assembly are registered to Iservicecollection/// </summary>        /// <param name= "Services" >iservicecollection</param>        /// <param name= "Aassemblyname" >assembly name</param>        /// <param name= "Wherelambda" >expressions for filtering types</param>         Public Static voidAutoregisterservicesfromassembly ( Thisiservicecollection Services,stringAassemblyname, Func<type,BOOL>Wherelambda) {            //gets all the types in the assembly based on the name of the assemblytype[] Types =Gettypesbyassemblyname (aassemblyname); //filtering the above assembly is filtered first according to the conditions passed in and then requires that the type must be a class and cannot be an abstract classienumerable<type> _types = types. Where (WHERELAMBDA). Where (t = T.isclass &&!t.isabstract); foreach(varTinch_types) {IEnumerable<Attribute> attrs =t.getcustomattributes (); //Traverse all attributes of a class                foreach(varattrinchattrs) {                    //If the attribute is found to be the Usediattribute attribute, the class is registered in the DI container.//and jump out of the current loop and start looping over the next class.                    if(attr isUsediattribute) {Services.                        Autoregisterservice (t);  Break; }                }            }        }        #endregion    }}

4. Register the assemblies that need to be processed in the Webapi Startup.cs class:

Using. NET Core to make unified dependency injection on classes in an assembly

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.