c# - Autofac ordered list as parameter -
i have object takes ordered list (iorderedenumerable) of items order of items 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 register orderedlistworker
autofac , ensure listitems in specifc order @ run time?
i see order isn't guaranteed in this post, i'm not sure how guarantee order.
i have solution, combination of iorderedenumerable
, , resolveordered<tcomponent>
solution post linked above.
using 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>( 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 registrations 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>()));
Comments
Post a Comment