C# Autofac:根据已注册的项目向容器添加新类型

C# Autofac:根据已注册的项目向容器添加新类型,c#,autofac,C#,Autofac,情境:我们有几个类,它们被注册为接口。这些类也用自定义属性标记。我们希望在App containew building的末尾检查所有注册的组件,并基于ot创建新的注册。比如说, [CustomAttribute] public class Foo: IFoo { [NewCustomActionAttribute("Show me your power!")] public void Do() {} } 所以我们正在做这个-builder.Register.As() 并将许多类

情境:我们有几个类,它们被注册为接口。这些类也用自定义属性标记。我们希望在App containew building的末尾检查所有注册的组件,并基于ot创建新的注册。比如说,

[CustomAttribute]
public class Foo: IFoo
{
    [NewCustomActionAttribute("Show me your power!")]
    public void Do() {}
}
所以我们正在做这个-
builder.Register.As()
并将许多类似的类转换成另一个插件。在注册了所有插件之后,我们希望将新类添加到构建器中,例如带有一些元数据(如标题和模块)的ICCustomAction,并在以后基于此注册加载它。 最好的方法是什么

更新:

var types = // get all registered types
foreach (var typeToProceed in types.Where(_ => _.GetCustomAttributes(typeof(CustomAttribute), false).FirstOrDefault != null)
{
   var customMethodAttributes = // Get NewCustomActionAttributes from this type
   for each customAttr
       builder.Register(new CustomClass(customAttr.Caption, dynamic delegate to associated method);
   end for aech
}

我不想在花瓶引导中这样做,因为可能还有很多其他属性。最好的方法是在首先需要此项(工具栏)时添加(仅一次)新类。

我将创建一个新的扩展方法
RegisterCustomClasses
,用于处理注册:

public static class AutofacExtensions
{
    public void RegisterCustomClasses<T>(this ContainerBuilder builder)
    {
        var methods = typeof(T).GetMethods();
        var attributes = methods.Select(x => new
                                        {
                                            Method = x,
                                            Attribute = GetAttribute(x)
                                        })
                                .Where(x => x.Attribute != null);

        foreach(var data in attributeData)
            builder.RegisterInstance(new CustomClass(data.Attribute.Caption, 
                                                     data.Method));
    }

    private static NewCustomActionAttribute GetAttribute(MethodInfo method)
    {
        return method.GetCustomAttributes(typeof(NewCustomActionAttribute))
                     .OfType<NewCustomActionAttribute>()
                     .FirstOrDefault()
    }
}
公共静态类AutofacExtensions
{
公共无效注册表自定义类(此ContainerBuilder生成器)
{
var methods=typeof(T).GetMethods();
var attributes=methods.Select(x=>new
{
方法=x,
Attribute=GetAttribute(x)
})
.Where(x=>x.Attribute!=null);
foreach(attributeData中的var数据)
builder.RegisterInstance(新CustomClass(data.Attribute.Caption,
数据处理方法);
}
私有静态NewCustomActionAttribute GetAttribute(MethodInfo方法)
{
return方法.GetCustomAttributes(typeof(NewCustomActionAttribute))
第()类
.FirstOrDefault()
}
}
用法:

builder.Register<Foo>.As<IFoo>();
builder.RegisterCustomClasses<Foo>();
builder.Register.As();
builder.RegisterCustomClasses();

示例代码中的
标题
模块
在哪里?标题是“展示您的力量!”,模块是定义此Foo类的模块的名称。我们想查看所有分配了NewCustomActionAttribute的公共方法,并添加新的注册。请用伪代码显示您希望对示例代码进行的注册。是否正确,您的问题是无法从
生成器
获取注册类?我的问题是,我知道通过模块进行搜索的最佳方法:)非常感谢!这种方法甚至比我想象的更好。