[. Net Core] Simple use of MVC built-in IOC (cont.)

Source: Internet
Author: User
Tags httpcontext

Simple use of MVC built-in IOC (cont.)

This article is based On. NET Core 2.0.

The previous chapter, "[. Net Core], Simple use of the MVC built-in ioc" has already illustrated the simple usage of the IOC in daily mvc, and there are some additions to it.

The next question revolves around these questions: what does the combination of Filter and Ioc look like in AOP? How do you get the instance object in the Ioc directly, instead of getting it in the form of a constructor?

Directory
    • Scenario One: Ioc Binding filter filters using
    • Scenario Two: Direct access to Ioc managed objects

Scenario One: Ioc Binding filter filters using

First write a filter ExceptionFilter.cs, inherit iexceptionfilter, mainly used for error logging, the namespace used is Microsoft.AspNetCore.Mvc.Filters.

usingMicrosoft.AspNetCore.Mvc.Filters;namespaceioccoredemo{ public classExceptionfilter:iexceptionfilter {Private ReadOnlyLogservice _logservice;  publicexceptionfilter (logservice logservice) {_logservice=logservice; }         public voidonexception (exceptioncontext Context) {_logservice.error (context.        exception.message); }    }}

LogService.cs the class of the print Log:

     public class Logservice    {        publicvoid Error (string  message)        {            Console.WriteLine ( message);        }    }

I'm testing it explicitly in the Index () method inside the controller Demo4Controller.cs to throw an exception that has not yet been implemented:

     public class Demo4controller:controller    {        public  iactionresult Index ()        {            thrownew  NotImplementedException ();        }    }

next, the code is modified within the Configureservices () method in the core Startup.cs, and the applet is injected using Addsingleton () as an example method:

         public voidconfigureservices (iservicecollection services) {services. Addsingleton (typeof(exceptionfilter));//Inject ExceptionfilterServices. Addsingleton (typeof(logservice));//Inject LogserviceServices. ADDMVC (x= {                //Create a ServiceProvider object                varProvider =Services.                Buildserviceprovider (); varFilter = Provider. Getservice<exceptionfilter>(); //Add FilterX.filters.add (filter);        }); }

After starting the program and jumping to the path http://localhost:port/demo4, we find that we can trigger the exception filter:

Scenario Two: Direct access to Ioc managed objects

Service class Demo5Service.cs for Testing:

     public class Demo5service    {        publicstring  Test ()        {            return  guid.newguid (). ToString ();        }    }

Method One

We can pass this within the Controller. HttpContext.RequestServices.GetService () Gets the service object that has been injected into the Ioc, such as Controller Demo5Controller.cs:

     public class Demo5controller:controller    {        public  iactionresult Index ()        {            var. HttpContext.RequestServices.GetService (typeof(demo5service));             return Json (demoservice.test ());        }    }

Don't forget to inject the service class into the Startup.cs:

Execution Result:

Method Two

By scene one know: the GetService () method in the ServiceProvider class can get an Ioc object that has already been injected, so we can consider starting with how to get the object (the serviceprovider class object).

below, I add a static ServiceProvider class member property in the Startup.cs class, which is easy to get externally:

     public classStartup { public StaticServiceProvider serviceprovider {Get;Private Set; } //this method gets called by the Runtime. Use this method to add services to the Container.         public voidconfigureservices (iservicecollection services) {services.            Addmvc (); Services. Addsingleton<Demo5Service>(); ServiceProvider=Services.        Buildserviceprovider (); }        //...}

After that, we can take this way to get the objects that have been injected in the Ioc:

     public class Demo5controller:controller    {        public  iactionresult Index ()        {            var demoservice = (demo5service) Startup.ServiceProvider.GetService (typeof(demo5service));             return Json (demoservice.test ());        }    }

Original: http://www.cnblogs.com/liqingwen/p/8585119.html

Related Articles:

"[. Net Core] Simple Read JSON configuration file"

[. Net Core] Simple to use MVC built-in Ioc "

[. Net Core] Simple to use MVC built-in IOC (cont.)

[. Net Core] simple to use MVC built-in IOC (cont.)

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.