眾所周知,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)) { //.. } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/57104.html
標籤:其他
上一篇:w10環境下Hexo博客搭建
