衆所周知,ASP.NET Core有一個DI架構,應用程式啟動時初始化。
預定義依賴
1: IApplicationBuilder:提供了配置應用程式的請求管道機制
2:ILoggerFactory:次類型提供了建立記錄器元件的模式
3:LHostinEnvironment:此類型提供管理應用程式運作的Web宿主環境的資訊。
注冊自定義依賴
為了注冊類型,需要讓系統知道如何将一個抽象類型解析為一個具體類型,這種映射可以是靜态設定,也可以是動态的。
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ICustomerService, CustomerService>();
}
每當請求一個實作了ICustomerService的類型的執行個體時,系統傳回CustomerService的一個執行個體,特别是,AddTransient方法確定了每次都會傳回CustomerSerivce類型的一個新執行個體。
靜态解析有時候有一定的局限性。事實上,如果需要根據運作時條件将類型T解析為不同的類型,它允許指定一個回調函數來解析依賴
public void ConfigureServices(IServiceCollection services)
services.AddTransient<ICustomerService>(provider=> {
var context = provider.GetRequiredService<IHttpContextAccessor>();
if (SomeRuntimeConditionHolds(context.HttpContext.User))
return new CustomerServiceMatchingRuntionCondition();
else
return new DefaultCustomerService();
});
收集配置資料
我們都知道之前的配置都是用web.config檔案類擷取配置,那麼在Core中他們提供了一個更加豐富,複雜的基礎結構。
它配置是基于 名稱-值 對清單。1:Json資料提供程式,2:環境變量提供程式,3:記憶體提供程式。4:自定義配置提供程式。
關于自定義配置,我們需要實作一個IConfigurationSource接口的類,但是,在實作的時候,還需要引用一個內建自ConfigurationProvider的自定義類
public class MyDatabaseConfigSoure : IConfigurationSource
{
public IConfigurationProvider Build(IConfigurationBuilder builder)
throw new MyDatabaseConfigProvider();
}
public class MyDatabaseConfigProvider : ConfigurationProvider
private const string ConnectionString = "";
public override void Load()
using (var db = new MyDatabaseContext(ConnectionString))
{
//..
}