前言
在上一篇文章中寫了如何在MVC中配置全局路由前綴,今天給大家介紹一下如何在在 json 文件中配置依賴注入。
在以前的 ASP.NET 4+ (MVC,Web Api,Owin,SingalR等)時候,都是提供了專有的接口以供使用第三方的依賴注入組件,比如我們常用的會使用 Autofac、Untiy、String.Net 等,這些第三放依賴注入組件基本上都提供了一套配置注入或者配置生命周期的方式,除了直接配置到類里面之外,還提供了要么使用 xml 文件,要么使用 json 等,那么在新的 ASP.NET Core 中微軟已經默認的給我們提供了一個依賴注入的功能,我們就不再需要借助于第三方組件來實現依賴注入了,但是有時候我們想在配置文件中來配置依賴注入,微軟本身的 DI 組件并沒有給我們提供一個可供配置的文件,那么我們就需要自己來實現這個配置項的功能。個人覺得其主要使用場景是一些在編譯時不能確定實現的,需要動態修改實現的地方。
下面就來看看應該如何來做這件事情吧。
Getting Started
首先,在應用程序中我們創建一個接口,以供 DI使用:
public interface IFoo
{
string GetInputString(string input);
}
然后,添加一個 IFoo
接口的實現 Foo
public class Foo : IFoo
{
public string GetInputString(string input)
{
return $"輸入的字符串為:{ input }";
}
}
接下來,我們需要把以上的 IFoo
接口和它的實現添加到 Startup.cs 文件中的ConfigureServices
方法中,ConfigureServices 主要是用來配置依賴注入服務的。然后通過該方法提供的ISerciceCollection
接口參數注入 Services。
public void ConfigureServices(IServiceCollection services)
{
services.Add(new ServiceDescriptor(serviceType: typeof(IFoo),
implementationType: typeof(Foo),
lifetime: ServiceLifetime.Transient));
}
這里,我們使用到了 IServiceCollection 里面的 Add 方法,添加一個生命周期為瞬態的 IFoo
的實現。瞬態就是說在每次請求的時候都將創建一個Foo
的實例。
以上是默認微軟為我們提供的添加依賴注入的方法,下面我們來看一下怎么來改造成我們需要的使用 json 文件的方式。
使用 json 文件配置 DI
當我們使用json文件配置依賴注入的時候,可以選擇新建一個json文件,也可以直接使用 appsettings.json 文件。現在我們就直接在 appsettings.json 文件中添加關于DI的配置了。
appsettings.json
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"DIServices": [
{
"serviceType": "[namesapce].IFoo",
"implementationType": "[namesapce].Foo",
"lifetime": "Transient"
}
]
}
首先,添加一個名為 “DIServices” 的數組節點,數組中包含一個或多個配置service的對象,serviceType
代表服務接口的類型,implementationType
接口的實現,lifetime
初始化實例的生命周期。
注意:配置文件中的類型必須為全名稱,即包含命名空間。
接下來,添加一個和Json文件配置項相對應的一個service類,這里我們需要使用 Newtonsoft 這個json庫。
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文件即可。
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));
}
}
然后我們測試一下是否是可用的。
測試
打開 HomeController.cs ,添加注入項:
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
的構造函數添加IFoo接口,然后在 About 的Action中使用。
運行程序,打開頁面,點擊 About標簽
總結
以上即為在 ASP.NET Core 中配置依賴注入到json文件中,這只是一個簡單的實例,不要用在生產環境中。在實際的項目中你還需要處理關于讀取配置異常情況,服務是否存在的異常情況,生命周期等等這些問題。
本文地址:http://www.cnblogs.com/savorboard/p/dotnetcore-json-config-di.html
作者博客:Savorboard
歡迎轉載,請在明顯位置給出出處及鏈接
文章列表