我有一个对象,该对象采用项目的有序列表(IOrderedEnumerable),其中项目的顺序很重要.
public class OrderedListWorker : IListWorker
{
private OrderedListWorker(IOrderedEnumerable<IListItem> orderedListItems)
{
foreach (var listItem in orderedListItems)
listItem.DoSomethingWhereOrderMatters();
}
}
我有多个IListItem类型的对象.
如何在Autofac中注册OrderedListWorker,并确保在运行时按特定顺序获取ListItems?
我看到This Post中不能保证订单,但是我不确定如何保证订单.
解决方法:
我有一个解决方案,它是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>()));