Home  >  Article  >  Backend Development  >  Detailed explanation of ASP.NET Core configuring dependency injection in JSON file

Detailed explanation of ASP.NET Core configuring dependency injection in JSON file

高洛峰
高洛峰Original
2017-02-07 11:38:421281browse

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 the use of third-party dependency injection components, such as our commonly used Using Autofac, Untiy, String.Net, etc., these third-party dependency injection components basically provide a set of configuration injection or configuration life cycle methods. In addition to directly configuring into classes, they also provide the use of xml files. Either use json, etc., then in the new ASP.NET Core, Microsoft has provided us with a dependency injection function by default, and we no longer need to rely on third-party components to implement dependency injection, but sometimes we want to To configure dependency injection in the configuration file, Microsoft's own DI component does not provide us 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 an IFoo interface Implement Foo

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

Next, we need to add the above IFoo interface and its implementation to the ConfigureServices method in the Startup.cs file. ConfigureServices is mainly used to configure dependency injection services of. Services are then injected 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 IFoo implementation with a transient life cycle. Transient means that an instance of Foo will be created every time it is requested.

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 array node named "DIServices". The array contains one or more objects that configure service. serviceType represents the service. The type of interface, the implementation of the implementationType interface, and the lifetime of the initialized instance.

Note: The type in the configuration file must be a 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 ConfigureServices and read the configured json file 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 and 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 the constructor of HomeController, and then in the Action of About use.

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

详解ASP.NET Core 在 JSON 文件中配置依赖注入

Summary

The above is how to configure dependency injection in ASP.NET Core json file, 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.

For more detailed information on ASP.NET Core configuring dependency injection in JSON files, please pay attention to 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