Autofac 注册根据 属性 键控的所有子类型

Autofac registering all subtypes keyed according to a property

以下场景:

public enum ChildType
{
    Type1,
    Type2,
    Type3
}

public abstract class MyParentClass
{
    public abstract ChildType Id { get; }
}

public class Child1 : MyParentClass
{
    public override ChildType Id { get { return ChildType.Type1; } }
} 

public class Child2 : MyParentClass
{
    public override ChildType Id { get { return ChildType.Type2; } }
} 

public class Child3 : MyParentClass
{
    public override ChildType Id { get { return ChildType.Type3; } }
} 

并且我想使用 autofac 来注册所有子类型,使用它们的 id 作为键,所以类似于:

builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(type => type.IsSubclassOf(typeof(MyParentClass)))
            .Keyed<MyParentClass>(c => c.Id)
            .SingleInstance();

现在显然上面的方法行不通了,但是有没有什么方法可以在不单独注册每个子类的情况下实现呢?然后我希望能够通过枚举访问它们,即在运行时,当我不知道枚举的值是什么时:

public static MyParentClass GetSubClassByEnum(ChildType id)
{
    AutofacHostFactory.Container.ResolveKeyed<MyParentClass>(id);
}

不幸的是,您可能无法使此设置正常工作,因为这是一个 chicken/egg 问题 - 您希望根据不可用的信息来解析对象...除非你解决了对象。

实现此功能的一种方法是使用属性而不是属性。属性在实例化类型之前可用,因此您可以将信息存储在那里并获得所需的结果。

Autofac 具有属性元数据支持,允许您创建自定义属性来提供此类信息。您可以创建一个继承的属性,并且每个 class 只允许一个实例。将其与默认值一起应用到您的基础 class,然后当您需要覆盖时,在派生的 class.

上应用一个新属性

There is plenty of documentation with examples on the Autofac doc site 显示如何使用它。