2017-03-16 46 views
2

我想通過一個asp.net核心MVC(mvc6?)項目中的所有可用ViewComponents列表進行搜索,像這樣。以列表形式訪問所有可用的ViewComponents

Default.cshtml爲ViewComponent

foreach (var section in Model.sections) 
{ 
    var sectionId = section.Id; 
    if (_siteSettings.AvailableComponents.Any(c => c == sectionId)) 
    { 
     @await Component.InvokeAsync(sectionId); 
    } 
    else 
    { 
     <p>Could not find component: @sectionId </p>    
    }   
} 

現在,我已設法通過手動註冊在可在運行時列表中的每個組件來做到這一點。但我想做到的是在每個組件類文件簡單地註冊的每個視圖組件,像這樣:

public class NewsList : ViewComponent 
{ 

    private ISiteSettings _siteSettings; 
    private string ComponentName = "NewsList"; 

    public NewsList(ISiteSettings siteSettings) 
    { 
     _siteSettings = siteSettings; 

     _siteSettings.AvailableComponents.Add(ComponentName); 
    } 


    public async Task<IViewComponentResult> InvokeAsync() 
    {    
     return View(); 
    } 
} 

的問題是,直到viewcomponent呈現每個viewcomponent的構造將不會被執行,我需要以某種方式「自動」註冊所有組件。那可能嗎?

+0

不知道是否有任何方法列出子類ViewComponent的所有類(假設您通過從項目中的ViewComponent繼承來創建視圖組件)。可以在中間件級別獲得這些視圖組件的列表嗎? –

回答

1

要做到這一點,你需要使用反射。使用Assembly,您可以獲取項目中的所有類型,然後篩選BaseTypetypeof(ViewComponent)的位置。

var listOfViewComponents = Assembly 
          .GetEntryAssembly() 
          .GetTypes() 
          .Where(x => x.GetTypeInfo().BaseType == typeof(ViewComponent)); 

希望這會有所幫助。

+0

美麗,像魅力一樣工作!我心中有所反思,但我認爲也許有一些爲ViewComponents構建的方式。 –

相關問題