在 asp.net mvc core 使用 di

本篇文章將介紹如何在 ASP.NET MVC Core 中使用 DI (Dependency injection)

在 ASP.NET 中使用 DI 有個很大的好處,就是在於使用某些元件時,可以方便抽換,而在 Controller 使用諸如 Repository 這類跟 DB 有關的元件,可以不必實體宣告,只要建立有相關參數的建構子即可,例如下列範例:

public HomeController(ITest1Service test1Service)
{
    _test1Service = test1Service;
}

不必煩惱如何建立這個實體,只要當做參數傳進來,背後實體的建立就交由 ASP.NET 去處理,當然這樣的便利,得在一開始執行的 Startup.cs 中撰寫像這樣的程式碼:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddTransient(typeof(ITest1Service), typeof(Test1Service));
    services.AddTransient(typeof(ITest2Service), typeof(Test2Service));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

當然,如果元件太多,一個一個的呼叫 AddTransient 太累人了,透過統一的命名規則,可以做下列的簡化:

foreach (Type type in System.Reflection.Assembly.GetExecutingAssembly().ExportedTypes.Where(t => t.Name.EndsWith("Service")))
{
    if (!type.IsInterface)
    {
        services.AddTransient(type.GetInterfaces().First(), type);
    }
}