Detailed Description: ASP. NET Core configures dependency injection in the JSON file, asp. netjson
Preface
In the previous article, I wrote how to configure the global routing prefix in MVC. Today I will introduce how to configure dependency injection in the json file.
In the previous ASP. NET 4 + (MVC, Web Api, Owin, SingalR, etc.), all provide proprietary interfaces for third-party dependency injection components, for example, we usually use Autofac, Untiy, String.. Net, these third-party dependency injection components basically provide a set of configuration injection or configuration lifecycle methods. In addition to directly configuring the configuration in the class, they also provide either the use of xml files, you can either use json or so on. in NET Core, Microsoft has provided us with a dependency injection function by default, So we no longer need to use third-party components to implement dependency injection, however, sometimes we want to configure dependency injection in the configuration file. Microsoft's DI component does not provide us with a configuration file, then we need to implement the configuration item Function on our own. I personally think that the main application scenarios are some areas where the implementation cannot be determined during compilation and needs to be modified dynamically.
Let's take a look at how to do this.
Getting Started
First, we create an interface in the application for DI:
public interface IFoo{ string GetInputString(string input);}
Then, add IFoo
Implement Foo
Public class Foo: IFoo {public string GetInputString (string input) {return $ "input string: {input }";}}
Next, we need IFoo
Interface and its implementation are added to the Startup. cs file.ConfigureServices
ConfigureServices is mainly used to configure the dependency injection service. Then,ISerciceCollection
Interface parameter injection 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 in IServiceCollection to Add a transient IFoo
. Transient means that each request will createFoo
.
The above method is provided by default by Microsoft to add dependency injection. Next we will look at how to transform it into the method we need to use json files.
Configure DI using a json File
When we use a json file to configure dependency injection, you can choose to create a new json file or directly use the etettings. json file. Now we can add the DI configuration 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". The array contains one or more service configuration objects,serviceType
Indicates the type of the service interface,implementationType
Interface implementation,lifetime
Initialize the life cycle of the instance.
Note:: The type in the configuration file must be full name, that is, including namespace.
Next, add a service class corresponding to the configuration items of the Json file. here we need to use the json library Newtonsoft.
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 in ConfigureServices
To read the configured json file.
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 can 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 to the HomeController constructor and use it in the Action of About.
Run the program, open the page, and click the "About" tab.
Summary
The above is to configure dependency injection to json files in ASP. NET Core. This is just a simple instance and should not be used in the production environment. In actual projects, you also need to handle read configuration exceptions, service exceptions, and lifecycles.