DDD Combat 8_2 uses unity Dependency Injection to implement the configuration of the interface corresponding to the implementation class

Source: Internet
Author: User

1. Create a new Diservice class under the Util class library

    /// <summary>    /// create a class that corresponds to the key    of the object inside the diservices configured in the configuration file /// </summary>     Public class Diservice    {        publicstringgetset;}          Public string Get Set ; }    }

2 Configuring interfaces and implementation classes to be dependent on injection in the Webapi Appsettings.json file

3 Installing Unity.container and unity.servicelocator two packages for Util Class library project NuGet

4. Create a service locator Servicelocator class

namespaceutil{ Public classServicelocator:iserviceprovider//IServiceProvider This interface is the system's own    {        Private ReadOnlyIunitycontainer container;  PublicServicelocator () {container=NewUnityContainer (); //to use Jobject, you must install the Newtonsoft.json package//read the configuration file to get a JSON object            varJsonservices = Jobject.parse (File.readalltext ("Appsettings.json"))["diservices"]; //turn the jsonservices above into a collection of list<diservice>            varRequestservices = jsonconvert.deserializeobject<list<diservice>>(Jsonservices.tostring ()); //Traversing service Objects            foreach(varRequestServiceinchrequestservices) {                //registering with the containercontainer.            Registertype (Type.GetType (Requestservice.interfacetype), Type.GetType (Requestservice.implementationtype)); }        }         PublicT getservice<t>()        {            returnContainer. Resolve<t>(); }        //The following method is required for the IServiceProvider interface.         Public ObjectGetService (Type servicetype) {returncontainer.        Resolve (servicetype); }                 PublicT getservice<t>(parameteroverrides parameters) {returnContainer. Resolve<t>(parameters); }    }}

5 using the Service locator to practice dependency injection

namespaceproduct.webapi.controllers{[Produces ("Application/json")] [Route ("api/product")]     Public classProductcontroller:controller {//once executed, this parameterless constructor completes the mapping of the interface and implementationServicelocator Servicelocator =NewServicelocator ();        [HttpPost] [Route ("addproduct")]         Publicresultentity<BOOL>addproduct ([frombody] addproductspudto addproductspudto) {varresult =Newresultentity<BOOL>(); //var productdbcontext =new productefcorecontext (); //var irepsotory = new Efcorerepository (productdbcontext); //var iproductrepsitory = new Productefcorerepository (productdbcontext);            varProductdbcontext = servicelocator.getservice<iproductcontext>(); //the following new Unity.Resolution.ParameterOverrides () {{"Context", productdbcontext}}//{ } there is {} because it is a parameters description may have more than one parameter object//{"Context", productdbcontext} The first context is because the formal parameter of the public efcorerepository (DbContext context) is the context//The value is the productdbcontext we're going to pass in.            varIrepsotory = servicelocator.getservice<irepository> (NewUnity.Resolution.ParameterOverrides () {{"Context", Productdbcontext}}); varIproductrepsitory = servicelocator.getservice<iproductrepository> (NewUnity.Resolution.ParameterOverrides () {{"Context", Productdbcontext}}); varAddproductspuusecase =Newaddproductspuusecase (Irepsotory, iproductrepsitory); Try{result=Addproductspuusecase.                Addproduct (addproductspudto); Result. Issuccess=true; Result.count=1; Result. MSG="Shelves Product Success"; }            Catch(Exception ex) {result. ErrorCode= -; Result. MSG=Ex.            Message; }            returnresult; }          }}

DDD Combat 8_2 uses unity Dependency Injection to implement the configuration of the interface corresponding to the implementation class

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.