是否可以通过Autofac组件扫描为多种键注册一种类型?

问题描述 投票:0回答:1

我正在尝试为AutoFac中的多个键(即3、4、5)注册类型(即MyClass)。因此,componentContext.ResolveKeyed<T>(3)componentContext.ResolveKeyed<T>(4)componentContext.ResolveKeyed<T>(5)都返回MyClass实例。我不确定如何执行此操作,因为Keyed<IMyClass>()需要类型而不是值。

builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .Where(type => type.IsAssignableTo<IMyClass>())
            .Keyed<IMyClass>(type => type.GetCustomAttribute<MyCustomAttribute>().VALUES)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

[MyCustomAttribute(3, 4, 5)]
class MyClass : IMyClass { }

class MyCustomAttribute : Attribute {
    public int[] VALUES { get; set; }

    public MyCustomAttribute(params int[] values) {
       this.Values = values;
    }
}
c# dependency-injection autofac
1个回答
0
投票

Autofac核心不支持此功能,但是您可以轻松地为您实现扩展方法。

© www.soinside.com 2019 - 2024. All rights reserved.