以列表的形式访问所有可用的视图组件

时间:2022-11-18 16:58:05

I would like to search through a list of all available ViewComponents in a asp.net core MVC (mvc6?) project, something like this.

我想搜索一个asp.net核心MVC (mvc6?)项目中所有可用视图组件的列表,类似这样的东西。

Default.cshtml for ViewComponent

违约。为ViewComponent cshtml

 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>            
    }        
}

Now, I have managed to do this by manually registering each component in a list that is available at runtime. But what I would like to accomplish is to register each view component simply in each component class file, like this:

现在,我通过在运行时可用的列表中手动注册每个组件来实现这一点。但是我想完成的是在每个组件类文件中注册每个视图组件,如下所示:

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();
    }
}

The problem is that the constructor of each viewcomponent will not be executed until the viewcomponent is rendered, I need all components to be registered "automatically" somehow. Is that possible?

问题是每个viewcomponent的构造函数在viewcomponent呈现之前不会被执行,我需要以某种方式“自动”注册所有的组件。这有可能吗?

1 个解决方案

#1


1  

To do this, you need to use reflection. Using Assembly, you can get all the Types in your project, and then filter where the BaseType is typeof(ViewComponent).

为此,您需要使用反射。使用Assembly,您可以获得项目中的所有类型,然后过滤BaseType所在的位置(ViewComponent)。

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

Hope this helps.

希望这个有帮助。

#1


1  

To do this, you need to use reflection. Using Assembly, you can get all the Types in your project, and then filter where the BaseType is typeof(ViewComponent).

为此,您需要使用反射。使用Assembly,您可以获得项目中的所有类型,然后过滤BaseType所在的位置(ViewComponent)。

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

Hope this helps.

希望这个有帮助。