Asp.net core 學習筆記 ( DI 依賴注入 )

比起 Angular 的依賴注入, core 的相對簡單許多, 容易明白 

所有 provider 都在 startup 裡配置. 

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<Business>(Configuration.GetSection("business"));
    services.Configure<Configuration.Email>(Configuration.GetSection("email"));

    services.AddEmail();
    // Razor template 
    services.AddSingleton<ICompositeViewEngine, CompositeViewEngine>();
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

    // Entity 
    services.AddScoped(_ => new DB(Configuration.GetConnectionString("DefaultConnection")));

    // hangfire
    services.AddHangfire(config =>
            config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));

    // MVC
    services.Configure<RazorViewEngineOptions>(options =>
    {
        options.ViewLocationExpanders.Add(new FeatureLocationExpander());
    });
    services.AddMvc();
}

 

controller 就通過 constructor 來注入就可以了. 

private readonly DB db;
private ICompositeViewEngine CompositeViewEngine { get; set; }
private ActionContext ActionContext { get; set; }
private IServiceProvider ServiceProvider { get; set; }
private ITempDataProvider TempDataProvider { get; set; }
private Configuration.Email EmailConfig { get; set; }

public DebugController(
    DB db,
    ICompositeViewEngine compositeViewEngine,
    IActionContextAccessor actionContextAccessor,
    IServiceProvider serviceProvider,
    ITempDataProvider tempDataProvider,
    IOptionsSnapshot<Configuration.Email> emailOptionsAccessor
)
{
    CompositeViewEngine = compositeViewEngine;
    ActionContext = actionContextAccessor.ActionContext;
    ServiceProvider = serviceProvider;
    TempDataProvider = tempDataProvider;
    EmailConfig = emailOptionsAccessor.Value;
    this.db = db;
}

provider 有 3 個級別 

AddSingleton

AddScoped

AddTransient

單列是說整個 App 用一個例項

Scope 一個 request 一個例項

transient 則是每一個注入一個例項

 

一個模組一般上會提供好多 Service 

那麼要讓 startup 乾淨一些的話,我們可以包裝起來 

就好像這樣  services.AddEmail();

做法是開一個擴充套件方法 

namespace Project.Email
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddEmail(
            this IServiceCollection services)
        {
            services.AddSingleton<ICompositeViewEngine, CompositeViewEngine>();
            services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
            services.AddScoped<EmailService, EmailService>();
            return services;
        }
    }

    public class EmailService
    {
        public EmailService()
        {


        }

        public string name { get; set; } = "dada";
    }
}

 

關鍵詞:services db public configuration get compositeviewengine 注入 private 一個 set

相關推薦:

從壹開始前後端分離【 .NET Core2.0 +Vue2.0 】框架之九 || 依賴注入IoC學習 + AOP介面程式設計初探

.Net Core快取元件(MemoryCache)原始碼解析

Swagger如何訪問Ocelot中帶許可權驗證的API

循序漸進學.Net Core Web Api開發系列【6】:配置文件appsettings.json

深入研究EF Core AddDbContext 引起的記憶體洩露的原因

ScalaPB(5):用akka-stream實現reactive-gRPC

.netCore2.0 程序集DI依賴注入

asp.net core 四 IOC&DI Autofac

【ASP.NET Core】MVC中自定義檢視的查詢位置

基於.netcore 開發的輕量Rpc框架