Home Backend Development C#.Net Tutorial Introduction to dependency injection methods in .NET configuration JSON

Introduction to dependency injection methods in .NET configuration JSON

May 13, 2017 am 11:28 AM
asp.net core json dependency injection

This article mainly introduces the detailed explanation of ASP.NET Core configuring dependency injection in JSON files. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Preface

In the previous article, I wrote how to configure global in MVC Routing prefix, today I will introduce to you how to configure dependency injection in a json file.

In the previous ASP.NET 4+ (MVC, Web Api, Owin, SingalR, etc.), proprietary interfaces were provided for use Third-party dependency injection components, for example, we commonly use Autofac, Untiy, String.Net, etc. These third-party dependency injection components basically provide a set of configuration injection or configuration life The cycle method, in addition to directly configuring it into the class, also provides the option of using xml files, or using json, etc. In the new ASP.NET Core, Microsoft has given us this by default Provides a dependency injection function, we no longer need to resort to third-party components to implement dependency injection, but sometimes we want to configure dependency injection in Configuration File, Microsoft's own DI component does not We are not provided with a configuration file, so we need to implement the function of this configuration item ourselves. Personally, I feel that its main usage scenarios are places where the implementation cannot be determined at compile time and the implementation needs to be modified dynamically.

Let’s take a look at how to do this.

Getting Started

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


1

2

3

4

public interface IFoo

{

  string GetInputString(string input);

}

Copy after login

Then, add a IFoo implementation of the interface Foo


##

1

2

3

4

5

6

7

public class Foo : IFoo

{

  public string GetInputString(string input)

  {

    return $"输入的字符串为:{ input }";

  }

}

Copy after login

Next, we need to add the above

The IFoo interface and its implementation are added to the ConfigureServices method in the Startup.cs file. ConfigureServices is mainly used to configure dependency injection services. Then inject Services through the ISerciceCollection interface parameter provided by this method.


1

2

3

4

5

6

public void ConfigureServices(IServiceCollection services)

{

  services.Add(new ServiceDescriptor(serviceType: typeof(IFoo),

                    implementationType: typeof(Foo),

                    lifetime: ServiceLifetime.Transient));

}

Copy after login

Here, we use the Add method in IServiceCollection to add an implementation of

IFoo with a transient life cycle. Transient means that an instance of Foo will be created every time a request is made.

The above is the default method of adding dependency injection provided by Microsoft. Let's take a look at how to transform it into the way we need to use json files.

Use json file to configure DI

When we use json file to configure dependency injection, we can choose to create a new json file or directly use the appsettings.json file. Now we will add the DI configuration directly to the appsettings.json file.

appsettings.json


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

"Logging": {

  "IncludeScopes": false,

  "LogLevel": {

   "Default": "Debug",

   "System": "Information",

   "Microsoft": "Information"

  }

 },

 

 "DIServices": [

  {

   "serviceType": "[namesapce].IFoo",

   "implementationType": "[namesapce].Foo",

   "lifetime": "Transient"

  }

 ]

}

Copy after login

First, add an

arraynode named "DIServices", which contains one or more A object that configures service, serviceType represents the type of service interface, implementationType the implementation of the interface, lifetime initializes the life cycle of the instance.

Note: The type in the configuration file must be the full name, that is, include the namespace.

Next, add a service class corresponding to the Json file configuration item. Here we need to use the Newtonsoft json library.



1

2

3

4

5

6

7

8

9

10

11

12

13

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; }

}

Copy after login

Then you need to modify the ConfigureServices, and

read the json file of the configuration in ConfigureServices .


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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));

  }

}

Copy after login

Then we test whether it is available.

Test

Open

HomeController.cs , add the injection item:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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();

  }

}

Copy after login
Add the IFoo interface in HomeController's

constructor , and then use it in About's Action.

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


##Summary

The above is to configure dependency injection into a json file in ASP.NET Core. This is just a simple example and should not be used in a production environment. In actual projects, you also need to deal with issues such as exceptions when reading configuration, whether the service exists, life cycle, etc.

【Related Recommendations】

1. Special Recommendation: "php Programmer Toolbox" V0.1 version download

2. ASP Free Video Tutorial

3. Li Yanhui ASP Basic Video Tutorial

The above is the detailed content of Introduction to dependency injection methods in .NET configuration JSON. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Dependency injection using JUnit unit testing framework Dependency injection using JUnit unit testing framework Apr 19, 2024 am 08:42 AM

For testing dependency injection using JUnit, the summary is as follows: Use mock objects to create dependencies: @Mock annotation can create mock objects of dependencies. Set test data: The @Before method runs before each test method and is used to set test data. Configure mock behavior: The Mockito.when() method configures the expected behavior of the mock object. Verify results: assertEquals() asserts to check whether the actual results match the expected values. Practical application: You can use a dependency injection framework (such as Spring Framework) to inject dependencies, and verify the correctness of the injection and the normal operation of the code through JUnit unit testing.

Dependency injection pattern in Golang function parameter passing Dependency injection pattern in Golang function parameter passing Apr 14, 2024 am 10:15 AM

In Go, the dependency injection (DI) mode is implemented through function parameter passing, including value passing and pointer passing. In the DI pattern, dependencies are usually passed as pointers to improve decoupling, reduce lock contention, and support testability. By using pointers, the function is decoupled from the concrete implementation because it only depends on the interface type. Pointer passing also reduces the overhead of passing large objects, thereby reducing lock contention. Additionally, DI pattern makes it easy to write unit tests for functions using DI pattern since dependencies can be easily mocked.

See all articles