search
HomeBackend DevelopmentC#.Net TutorialIntroduction 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.netcorejsondependency 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:


public interface IFoo
{
  string GetInputString(string input);
}

Then, add a IFoo implementation of the interface Foo


##

public class Foo : IFoo
{
  public string GetInputString(string input)
  {
    return $"输入的字符串为:{ input }";
  }
}

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.


public void ConfigureServices(IServiceCollection services)
{
  services.Add(new ServiceDescriptor(serviceType: typeof(IFoo), 
                    implementationType: typeof(Foo), 
                    lifetime: ServiceLifetime.Transient));
}

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


 "Logging": {
  "IncludeScopes": false,
  "LogLevel": {
   "Default": "Debug",
   "System": "Information",
   "Microsoft": "Information"
  }
 },

 "DIServices": [
  {
   "serviceType": "[namesapce].IFoo",
   "implementationType": "[namesapce].Foo",
   "lifetime": "Transient"
  }
 ]
}

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.



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 modify the ConfigureServices, and

read the json file of the configuration in ConfigureServices .


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 test whether it is available.

Test

Open

HomeController.cs , add the injection item:


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 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
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
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor