很抱歉回答晚了,但是是的,你可以这样做。
要使用动态组件,请按以下步骤操作:
- 使用
Assembly.LoadfFrom(assemblyFilename) 加载程序集
- 在 .razor 文件中,使用 blazor 渲染树构建器动态渲染组件,如下所示:
RenderFragment EditContent = (__builder) =>
{
__builder.OpenComponent(0, TypeOfYourComponent);
__builder.AddAttribute(1, "attr1", attrValue);
...
__builder.AddAttribute(n, "attrn", attrNValue);
__builder.CloseComponent();
};
@EditContent
- 实现从当前加载的程序集中返回所需类型的方法。下面将为您提供一个列表,其中包含由动态加载的程序集导出的所有类型:
var exportedTypes = new List<Type>();
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
foreach (var assembly in assemblies)
{
exportedTypes.AddRange(assembly.GetExportedTypes().ToList());
}
在我的例子中,我创建了一个单例,它在初始化时从文件夹加载程序集,并在此单例中创建了一个方法来返回步骤 3 中定义的列表中的类型。因此,通过这种方式,您可以通过在 Startup.cs 上注册并将其注入您的剃须刀组件,随时调用此服务:
public class CustomComponentService : ICustomComponentService
{
public CustomComponentService(...)
{
// load the assemblies here
}
public Type GetCustomComponent(...)
{
//search in the loaded assemblies by any criteria you like
}
}
在 Startup.cs 的 ConfigureServices 方法中:
_ = services.AddSingleton<ICustomComponentService, CustomComponentService>();
在剃刀文件中:
@inject ICustomComponentService CustomComponentService
...
__builder.OpenComponent(0, CustomComponentService.GetCustomComponent(...));
...