簡體   English   中英

使用 AutoFac 獲取 IRepository 的已解決依賴項

[英]Get resolved dependancies of IRepository with AutoFac

接口設置如下:

public interface IRepository { };

public interface IFirstRepository : IRepository { };
public interface ISecondRepository : IRepository { };
public interface IThirdRepository : IRepository { };

還有一個需要一些但不是全部這些存儲庫的控制器:

public class TestController : BaseController 
{
    private IFirstRepository mFirstRepository;
    private ISecondRepository mSecondRepository;
    // Standard DI for MVC 
    public TestController(IFirstRepository first, ISecondRepository second)
    {
        mFirstRepository = first;
        mSecondRepository = second;
    }
}

BaseController看起來像:

public class BaseController : Controller {
     public IEnumerable<IRepository> GetRepos()
     {
         // One solution is to use reflection 
         // to get all properties that are IRepositories.
         // Something along the lines of;
         return typeof(this).GetProperties().Where(prop=>prop is IRepository);

         // But is there a way to use the AutoFac context
         // to get the repos, rather than use reflection?
         // it surely already has that info since it
         // was able to call the constructor correctly?
     }
}

有沒有辦法BaseController可以利用 AutoFac 上下文和現有信息來獲取TestController請求的IRepository實例的集合?

Autofac 肯定已經擁有該信息,因為它能夠使用正確的實例調用構造函數。

注意:我不只是在這里使用反射的唯一原因是性能問題。

沒有一種簡單的方法可以開箱即用。 如果您發現自己處於這種情況,通常意味着您有界面設計問題。 有一個常見問題解答介紹了為什么會這樣,以及一些選項。

如果您真的真的需要這樣做,那么我可能會考慮將元數據添加到每個注冊中,其中每個控制器都有一個元數據條目,需要該特定存儲庫,然后使用元數據過濾器屬性在構造函數中進行過濾 同樣, 我提到的常見問題解答對此進行了介紹並展示了示例。

但如果是在這個系統中工作......我會退后一步,看看我的界面設計,看看如何從一開始就不需要這種過濾器。 如果它們不能一視同仁(Liskov 替換原則),則表明需要不同的接口。

暫無
暫無

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

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