. NET configuration JSON to introduce the method of dependency injection

Source: Internet
Author: User
This article mainly introduces the detailed description of ASP. NET Core in the JSON file configuration Dependency Injection, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

Objective

In the previous article on how to configure the global routing prefix in MVC, let's show you how to configure dependency injection in a JSON file today.

In previous ASP. NET 4+ (Mvc,web api,owin,singalr, etc.), we provided a proprietary interface for use of third-party dependency injection components, for example, we used to use AUTOFAC, untiy, string.net, etc. These third-place dependency injection components basically provide a set of configuration injection or configuration lifecycle methods, in addition to directly configured in the class, but also provide either the use of XML files, or use JSON, and so on the new ASP. Microsoft has provided us with a dependency injection function by default, we no longer need to use third-party components to implement dependency injection, but sometimes we want to configure the dependency injection in the configuration file, Microsoft's own DI component does not provide us with a configurable file, Then we need to implement the functionality of this configuration item ourselves. Personally, the main use of the scene is some in the compile time can not be determined to implement, need to dynamically modify the implementation of the place.

Let's take a look at how we can do this thing.

Getting Started

First, in the application we create an interface for Di to use:


Public interface ifoo{  string getinputstring (string input);

Then, add an IFoo implementation of the interface Foo


public class foo:ifoo{public string  getinputstring (string input)  {    return $ "The string entered is: {input}";  }}

Next, we need to add the above IFoo interface and its implementation to the method in the Startup.cs file ConfigureServices , configureservices is mainly used to configure the dependency injection service. The interface parameters provided by this method are then ISerciceCollection injected into Services.


public void Configureservices (iservicecollection services) {  services. ADD (New Servicedescriptor (Servicetype:typeof (IFoo),                     implementationtype:typeof (Foo),                     lifetime: servicelifetime.transient));}

Here, we use the Add method inside the iservicecollection to add an implementation with a transient life cycle IFoo . Transient means that an instance will be created each time the request is made Foo .

The above is the default Microsoft provides us with the method of adding dependency injection, let's look at how to change the way we need to use the JSON file.

Configuring DI with a JSON file

When we use JSON files to configure dependency injection, you can choose to create a new JSON file or use the Appsettings.json file directly. Now we add the configuration about di directly in the Appsettings.json file.

Appsettings.json


"Logging": {  "includescopes": false,  "LogLevel": {   "Default": "Debug", "   System": "Information",   "Microsoft": "Information"  } }, "Diservices": [  {   "servicetype": "[Namesapce]. IFoo ",   " Implementationtype ":" [Namesapce]. Foo ",   " lifetime ":" Transient "  }]}

First, add an array node named "Diservices" that contains one or more objects that configure the service, representing the type of the serviceType interface, implementationType the implementation of the interface, and the lifetime life cycle of the initialization instance.

Note : The type in the configuration file must be a full name, which includes the namespace.

Next, add a service class corresponding to the JSON file configuration item, where we need to use the Newtonsoft JSON library.


Using microsoft.extensions.dependencyinjection;using newtonsoft.json;using Newtonsoft.json.converters;public class service{public  string ServiceType {get; set;}  public string Implementationtype {get;set;}  [Jsonconverter (typeof (Stringenumconverter))]  Public Servicelifetime Lifetime {get; set;}}

Then you need to retrofit the configureservices and ConfigureServices read the configured JSON file in.


public void Configureservices (iservicecollection services) {  //services. ADD (New Servicedescriptor (Servicetype:typeof (IFoo),  //            implementationtype:typeof (Foo),  //            lifetime:ServiceLifetime.Transient));  var jsonservices = Jobject.parse (File.readalltext ("Appsettings.json")) ["Diservices"];  var requiredservices = jsonconvert.deserializeobject<list<service>> (jsonservices.tostring ());  foreach (var service in requiredservices) {    services. ADD (New Servicedescriptor (ServiceType:Type.GetType) (service. servicetype),                      implementationType:Type.GetType (service. Implementationtype),                      Lifetime:service. Lifetime));}  }

Then we'll test if it's available.

Test

Open HomeController.cs , add injected items:


public class homecontroller:controller{  private readonly IFoo _foo;  Public HomeController (IFoo foo)   {    _foo = foo;  }  Public Iactionresult About ()   {    viewdata["Message"] = _foo. GetInputString ("Your Application description page.");    return View ();}  }

Add the IFoo interface to the HomeController constructor, and then use it in the about action.

Run the program, open the page, click on the About tab

Summarize

The above is to configure dependency injection in ASP. NET Core into a JSON file, which is a simple instance that is not used in a production environment. In the actual project you also need to deal with the problems of reading configuration anomalies, the existence of service anomalies, the life cycle and so on.

"Recommended"

1. Special recommendation : "PHP Programmer Toolkit" V0.1 version download

2. asp free Video Tutorial

3. Eon the ASP Basic video tutorial

Related Article

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.