Autofac ordered list as parameter

autofac, c#

Solution

I have a solution, that is a combination of the `IOrderedEnumerable`, and the `ResolveOrdered<TComponent>` solution from the post I linked to above.

Using the AutofacExtensions Class:

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);
    }
}

I can specify my registrations as follows:

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>()));

Problem

I have an object that takes an ordered List (IOrderedEnumerable) of items where the order of the items is important. ``` public class OrderedListWorker : IListWorker { private OrderedListWorker(IOrderedEnumerable<IListItem> orderedListItems) { foreach (var listItem in orderedListItems) listItem.DoSomethingWhereOrderMatters(); } } ``` I have multiple objects of type `IListItem`. How can I register `OrderedListWorker` with Autofac and ensure that I get the ListItems in a specifc order at run time? I see that order isn't guaranteed in This Post, but I'm not sure how to guarantee order.

Original source

Related problems