我有一个解决方案,它是IOrderedEnumerable
, 和ResolveOrdered<TComponent>
我上面链接到的帖子中的解决方案的组合。
使用 AutofacExtensions 类:
public static class AutofacExtensions
{
private const string OrderString = "WithOrderTag";
private static int _orderCounter;
public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle>
WithOrder<TLimit, TActivatorData, TRegistrationStyle>(
this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> registrationBuilder)
{
return registrationBuilder.WithMetadata(OrderString, Interlocked.Increment(ref _orderCounter));
}
public static IOrderedEnumerable<TComponent> ResolveOrdered<TComponent>(this IComponentContext context)
{
return
context.Resolve<IEnumerable<Meta<TComponent>>>()
.OrderBy(m => m.Metadata[OrderString])
.Select(m => m.Value).OrderBy(c => true);
}
}
我可以指定我的注册如下:
builder.RegisterType<ListItemA>().As<IListItem>().WithOrder();
builder.RegisterType<ListItemB>().As<IListItem>().WithOrder();
builder.RegisterType<OrderedListWorker>()
.As<IListWorker>()
.WithParameter(
new ResolvedParameter(
(info, context) => true,
(info, context) => context.ResolveOrdered<IListItem>()));