简体   繁体   English

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

[英]Autofac: add new types to container based on already registered items

Situation: We have several classes, which are registred as interface. 情况:我们有几个类,它们被注册为接口。 Also this classes are marked with custom attribute. 此外,此类还标记有自定义属性。 We want to go throught all registered components in the end of App containew building and create new registrations based on ot. 我们要遍历应用程序包含构建末尾的所有注册组件,并基于ot创建新注册。 For example, 例如,

[CustomAttribute]
public class Foo: IFoo
{
    [NewCustomActionAttribute("Show me your power!")]
    public void Do() {}
}

So we are doing this - builder.Register<Foo>.As<IFoo>(); 所以我们正在这样做builder.Register<Foo>.As<IFoo>();
And a lot of the similar classes into another plugins. 并将许多类似的类插入另一个插件。 After all plugins beeing registered, we want to add new class to builder, eg ICustomAction with some metadata like caption and module, and load it later based on this registration. 在所有插件都注册之后,我们希望向构建器添加新类,例如ICustomAction,其中包含一些标题和模块等元数据,并在以后基于此注册将其加载。 What is the best way to do that? 最好的方法是什么?

UPDATE: 更新:

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
}

I do not want to do it in the vase bootstrap, because there may be a lot of another attributes. 我不想在花瓶引导程序中执行此操作,因为可能还有很多其他属性。 The best way is to add (only once) new classes when this item (Toolbar) is requsted first. 最好的方法是在首先要求此项(工具栏)时添加(仅一次)新类。

I would create a new extension method RegisterCustomClasses that handles the registration: 我将创建一个新的扩展方法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()
    }
}

Usage: 用法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM