前言
在上一篇文章中寫(xiě)了如何在MVC中配置全局路由前綴,今天給大家介紹一下如何在在 json 文件中配置依賴注入。
在以前的 ASP.NET 4+ (MVC,Web Api,Owin,SingalR等)時(shí)候,都是提供了專有的接口以供使用第三方的依賴注入組件,比如我們常用的會(huì)使用 Autofac、Untiy、String.Net 等,這些第三放依賴注入組件基本上都提供了一套配置注入或者配置生命周期的方式,除了直接配置到類里面之外,還提供了要么使用 xml 文件,要么使用 json 等,那么在新的 ASP.NET Core 中微軟已經(jīng)默認(rèn)的給我們提供了一個(gè)依賴注入的功能,我們就不再需要借助于第三方組件來(lái)實(shí)現(xiàn)依賴注入了,但是有時(shí)候我們想在配置文件中來(lái)配置依賴注入,微軟本身的 DI 組件并沒(méi)有給我們提供一個(gè)可供配置的文件,那么我們就需要自己來(lái)實(shí)現(xiàn)這個(gè)配置項(xiàng)的功能。個(gè)人覺(jué)得其主要使用場(chǎng)景是一些在編譯時(shí)不能確定實(shí)現(xiàn)的,需要?jiǎng)討B(tài)修改實(shí)現(xiàn)的地方。
下面就來(lái)看看應(yīng)該如何來(lái)做這件事情吧。
Getting Started
首先,在應(yīng)用程序中我們創(chuàng)建一個(gè)接口,以供 DI使用:
1
2
3
4
|
public interface IFoo { string GetInputString( string input); } |
然后,添加一個(gè) IFoo
接口的實(shí)現(xiàn) Foo
1
2
3
4
5
6
7
|
public class Foo : IFoo { public string GetInputString(string input) { return $ "輸入的字符串為:{ input }" ; } } |
接下來(lái),我們需要把以上的 IFoo
接口和它的實(shí)現(xiàn)添加到 Startup.cs 文件中的ConfigureServices
方法中,ConfigureServices 主要是用來(lái)配置依賴注入服務(wù)的。然后通過(guò)該方法提供的ISerciceCollection
接口參數(shù)注入 Services。
1
2
3
4
5
6
|
public void ConfigureServices(IServiceCollection services) { services.Add( new ServiceDescriptor(serviceType: typeof (IFoo), implementationType: typeof (Foo), lifetime: ServiceLifetime.Transient)); } |
這里,我們使用到了 IServiceCollection 里面的 Add 方法,添加一個(gè)生命周期為瞬態(tài)的 IFoo
的實(shí)現(xiàn)。瞬態(tài)就是說(shuō)在每次請(qǐng)求的時(shí)候都將創(chuàng)建一個(gè)Foo
的實(shí)例。
以上是默認(rèn)微軟為我們提供的添加依賴注入的方法,下面我們來(lái)看一下怎么來(lái)改造成我們需要的使用 json 文件的方式。
使用 json 文件配置 DI
當(dāng)我們使用json文件配置依賴注入的時(shí)候,可以選擇新建一個(gè)json文件,也可以直接使用 appsettings.json 文件。現(xiàn)在我們就直接在 appsettings.json 文件中添加關(guān)于DI的配置了。
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" } ] } |
首先,添加一個(gè)名為 “DIServices” 的數(shù)組節(jié)點(diǎn),數(shù)組中包含一個(gè)或多個(gè)配置service的對(duì)象,serviceType
代表服務(wù)接口的類型,implementationType
接口的實(shí)現(xiàn),lifetime
初始化實(shí)例的生命周期。
注意:配置文件中的類型必須為全名稱,即包含命名空間。
接下來(lái),添加一個(gè)和Json文件配置項(xiàng)相對(duì)應(yīng)的一個(gè)service類,這里我們需要使用 Newtonsoft 這個(gè)json庫(kù)。
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 ; } } |
然后需要改造一下ConfigureServices,在 ConfigureServices
中讀取配置的 json文件即可。
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)); } } |
然后我們測(cè)試一下是否是可用的。
測(cè)試
打開(kāi) HomeController.cs
,添加注入項(xiàng):
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(); } } |
在 HomeController的構(gòu)造函數(shù)添加IFoo接口,然后在 About 的Action中使用。
運(yùn)行程序,打開(kāi)頁(yè)面,點(diǎn)擊 About標(biāo)簽

總結(jié)
以上即為在 ASP.NET Core 中配置依賴注入到j(luò)son文件中,這只是一個(gè)簡(jiǎn)單的實(shí)例,不要用在生產(chǎn)環(huán)境中。在實(shí)際的項(xiàng)目中你還需要處理關(guān)于讀取配置異常情況,服務(wù)是否存在的異常情況,生命周期等等這些問(wèn)題。
原文鏈接:http://www.cnblogs.com/savorboard/p/dotnetcore-json-config-di.html