Let me 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 implementation of the IFoo 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 Configureservices method in the Startup.cs file, Configureservices is mainly used to configure the dependency injection service. The Isercicecollection interface parameters provided by this method are then injected into the 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 of the IFoo with a life cycle transient. Transient means that an instance of Foo is created each time the request is made.
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, ServiceType represents the type of the services interface, the implementation of the Implementationtype interface, lifetime Initializes the life cycle of the 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 read the configured JSON file in the 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'll test if it's available.
Test
Open HomeController.cs and add the injected 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 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.