Autofac排序列表作为参数
本文关键字:参数 列表 排序 Autofac | 更新日期: 2023-09-27 18:24:52
我有一个对象,它接受项目的有序列表(IOrderedEnumerable),其中项目的顺序很重要。
public class OrderedListWorker : IListWorker
{
private OrderedListWorker(IOrderedEnumerable<IListItem> orderedListItems)
{
foreach (var listItem in orderedListItems)
listItem.DoSomethingWhereOrderMatters();
}
}
我有多个类型为IListItem
的对象。
如何向Autofac注册OrderedListWorker
并确保在运行时以特定顺序获得ListItems?
我在这篇文章中看到订单没有保证,但我不知道如何保证订单。
我有一个解决方案,它是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>()));
我知道这是一个老问题,但我今天遇到了类似的问题,我想分享我的解决方案。
注册:
protected override void Load(ContainerBuilder builder)
{
builder.RegisterOrdered<IListItem>(scope =>
{
scope.Register<Item1>();
scope.Register<Item2>();
});
}
基础设施:
public static class AutofacExtensions
{
public static void RegisterOrdered<TService>(this ContainerBuilder builder, Action<IOrderedScope> setter)
{
var scope = new OrderedScope<TService>(builder);
setter(scope);
builder.Register(ctx => ctx.Resolve<IEnumerable<TService>>().OrderBy(x => scope.OrderedTypes[x.GetType()]));
}
private class OrderedScope<TService> : IOrderedScope
{
private readonly ContainerBuilder _builder;
private int _order = 1;
public OrderedScope(ContainerBuilder builder)
{
_builder = builder;
OrderedTypes = new Dictionary<Type, int>();
}
public Dictionary<Type, int> OrderedTypes {get;}
public IRegistrationBuilder<T, ConcreteReflectionActivatorData, SingleRegistrationStyle> Register<T>()
{
OrderedTypes.Add(typeof(T), _order++);
return _builder.RegisterType<T>().As<TService>();
}
}
}
public interface IOrderedScope
{
IRegistrationBuilder<T, ConcreteReflectionActivatorData, SingleRegistrationStyle> Register<T>();
}
用法:
public class OrderedListWorker : IListWorker
{
public OrderedListWorker(IOrderedEnumerable<IListItem> items)
{
}
}