Using the IOC Trilogy in ASP (I.. IOC container with ASP. NET Core)

Source: Internet
Author: User

Preface

This article focuses on the usage and injection type lifecycle of the IOC container that comes with it in ASP.

In this case, we will not dwell on what the IOC is and what di is. EMM: Do not know can self-Baidu.

Directory

Using the IOC Trilogy in ASP (I.. IOC container with ASP. NET Core)

Using the IOC Trilogy in ASP. Two. Replace the IOC container with AUTOFAC and implement attribute injection)

Using the IOC Trilogy in ASP. Three. Using the replaced AUTOFAC to implement AOP interception

Body

Today we mainly talk about how to use the self-brought IOC container, EMM. Although the feature is not so powerful, but wins in the lightweight. And.. Do not reference other libraries.

In the new ASP. NET core, a large number of methods of dependency injection are used to write code.

For example, in the configureservices of our startup class, we can see:

Addmvc Adddbcontext includes the adddirectorybrowser used in our previous catalogue tour.

is the framework to provide good service , we directly injected can be used.

1. How to inject your own services

Let's talk about how to inject our services.

First, we write our own testing services as follows:

     Public classTestservice:itestservice { PublicTestservice () {MyProperty=Guid.NewGuid (); }         PublicGuid MyProperty {Get;Set; }  Publiclist<string> GetList (stringa) {return Newlist<string> () {"Lilei","Zhangsan","LiSi" }; }    }

Write the corresponding interface code as follows:

     Public Interface Itestservice    {        get;}        List<string> GetList (string  a);    }

Then, we are going to reference Microsoft.Extensions.DependencyInjection (PS, which is very straightforward in the startup class). Microsoft.. Extended... Dependency Injection--,)

Modify the Configureservices method as follows:

         Public void configureservices (iservicecollection services)        {            services. Addmvc ();            Services. Adddbcontext<BloggingContext>();              // This is the injection service            . Services. Addtransient<itestservice, testservice>();            Services. Adddirectorybrowser ();        }

AddTransient is one of the methods of injection, the generic parameter, the first one is the interface you serve, the second is the implementation class of the service.

In this way, we have completed the initial injection operation.

So how do we use the services we inject?

We go to the controller and write the code as follows:

 public  class   Ditestcontroller:controller { private readonly   Itestservice _testservice;  public   Ditestcontroller (itestservice             Testservice) {_testservice  = Testservice;             public   Iactionresult Index () {Viewbag.date  = _testservice.getlist ( );              return   View (); }    }

There are generally three kinds of injection methods, constructor injection, method injection, and attribute injection. Microsoft comes with this IOC container, the default is the method of constructor injection (property injection is not supported, but can be implemented with third-party container substitution, the next chapter)

We write our index view as follows:

@{    viewdata["Title" "Index";} @foreach (var in viewbag.date) {    

}

The final effect is as follows:

2. the life cycle of the injection service

Microsoft provides 3 life cycles for self-injected services.

Transient (instantaneous)

the instantaneous life cycle service that is created each time the request is made. This life cycle is best suited for lightweight, stateless services.

Scoped (scoped)

At the same scope, the service is created only once for each request.

Singleton (Unique)

The global is created only once, is created the first time it is requested, and is used all the time.

How do you use these three life cycles? We can do this directly when we inject it in different ways, the code is as follows:

Services. Addtransient<itestservice, testservice>(); services. addscoped<itestservice2, testservice2>(); services. Addsingleton<itestservice3, testservice3> ();

Now, let's test the specific generation of these three life cycles.

We write three different names with the following interfaces:

     Public InterfaceItestservice {Guid MyProperty {Get; } List<string> GetList (stringa); }     Public InterfaceITestService2 {Guid MyProperty {Get; } List<string>GetList (); }     Public InterfaceITestService3 {Guid MyProperty {Get; } List<string>GetList (); }

Then use 3 classes to implement them separately.

 Public classTestservice:itestservice { PublicTestservice () {MyProperty=Guid.NewGuid (); }         PublicGuid MyProperty {Get;Set; }  Publiclist<string> GetList (stringa) {return Newlist<string> () {"Lilei","Zhangsan","LiSi" }; }    }     Public classTestservice2:itestservice2 { PublicTestService2 () {MyProperty=Guid.NewGuid (); }         PublicGuid MyProperty {Get;Set; }  Publiclist<string>GetList () {return Newlist<string> () {"Lilei","Zhangsan","LiSi" }; }    }     Public classTestservice3:itestservice3 { PublicTestService3 () {MyProperty=Guid.NewGuid (); }         PublicGuid MyProperty {Get;Set; }  Publiclist<string>GetList () {return Newlist<string> () {"Lilei","Zhangsan","LiSi" }; }    }

In the constructor of each implementation class, we have created a new GUID that, by this GUID, we can tell whether the class has ever re-executed the constructor or not.

We write the injected code as follows:

         Public void configureservices (iservicecollection services)        {            services. Addmvc ();            Services. Adddbcontext<BloggingContext>();            Services. AddTransient<itestservice, testservice>();            Services. addscoped<itestservice2, testservice2>();            Services. Addsingleton<itestservice3, testservice3>();            Services. Adddirectorybrowser ();        }

We modify the controller as follows:

     Public classDitestcontroller:controller {Private ReadOnlyItestservice _testservice; Private ReadOnlyITestService2 _testservice2; Private ReadOnlyITestService3 _testservice3;  PublicDitestcontroller (Itestservice testservice, ITestService2 testService2, ITestService3 testService3) { _testservice=Testservice; _testservice2=TestService2; _testservice3=TestService3; }        //The action injection method is used here.         Publiciactionresult Index ([Fromservices]itestservice testService11, [Fromservices]itestservice2 testService22) { Viewbag.date= _testservice.getlist (""); Viewbag.guid=_testservice.myproperty; Viewbag.guid11=Testservice11.myproperty; Viewbag.guid2=_testservice2.myproperty; Viewbag.guid22=Testservice22.myproperty; VIEWBAG.GUID3=_testservice3.myproperty; returnView (); }}

Here we take the action injection method and inject a new ITestService2 to ensure that 2 ITestService2 are in the same scope.

We write the relevant index page to show this information as follows:

@{viewdata["Title"] = "Index";}<H2>Index</H2>@foreach (var item in viewbag.date) {<H2>@item</H2>}<H1>Instantaneous: @ViewBag. Guid</H1><H1>Instantaneous 2: @ViewBag. Guid11</H1><H1>Scope: @ViewBag. Guid2</H1><H1>Scope 2: @ViewBag. guid22</H1><H1>Globally unique: @ViewBag. guid3</H1>

We run the code, the first access, the effect is as follows:

We found that the 2-generation GUIDs were inconsistent for the instantaneous life cycle, stating that the object was not the same.

The scope life cycle, however, because 2 times the GUID used by the service is consistent under the same scope, the same object is used.

We directly refresh the page for a second visit.

The effect is as follows:

Instantaneous and scoped, all continue to meet our expectations,

The globally unique life cycle is consistent with the GUID of the first access above. Describes the same object that was used by the 2 accesses. It is also in line with our expectations.

written in the last

This is the end of this article, and next we explain how to use a third-party AUTOFAC to replace our default IOC container, and use AUTOFAC's attribute injection to inject our services. Like, please point a recommendation and attention, ~ There are problems and I hope you criticize.

Using the IOC Trilogy in ASP (I.. IOC container with ASP. NET Core)

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.