簡體   English   中英

對基類的依賴注入

[英]Dependency injection on base class

為從類 A 繼承的類 B 設置 DI 是否可行,該類又實現了接口 I,如下所示:

public interface I {
 SomeMethod();
}

public abstract class A : I {
//some code ...
}

public class B : A {
//some code...
}

問題是 DI 會在這樣的方案上工作嗎,我的意思是為 B 類設置 DI?

通常 DI 容器(例如 Castle、Unity、Autofac 等)讓您區分類型注冊和接口鏈接。

在 Autofac 中,您可以注冊單一類型並聲明一些基類和接口:

builder.RegisterType<B>()
       .AsSelf()
       .As<A>()
       .As<I>();

現在當你需要B類、 A類或I接口時,會解析B類的實例。

如果你使用的是 ASP.NET Core,你可以簡單地使用一個通用的 Base Controller 類:

public abstract class BaseController<T> : Controller
{
    private IFoo _fooInstance;
    private IBar _barInstance;

    protected IFoo _foo => _fooInstance ??= HttpContext.RequestServices.GetService<IFoo>();
    protected IBar _bar => _barInstance ??= HttpContext.RequestServices.GetService<IBar>();
}

如果您使用的是 Razor 頁面:

class BasePageModel<T> : PageModel where T : class
{
    private IFoo _fooInstance;
    private IBar _barInstance;

    protected IFoo _foo => _fooInstance ??= HttpContext.RequestServices.GetService<IFoo>();
    protected IBar _bar => _barInstance ??= HttpContext.RequestServices.GetService<IBar>();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM