|
16 | 16 | - [Meta or Tuple of A with Metadata](#meta-or-tuple-of-a-with-metadata)
|
17 | 17 | - [Dictionary Metadata](#dictionary-metadata)
|
18 | 18 | - [IEnumerable or array of A](#ienumerable-or-array-of-a)
|
| 19 | + - [Custom order of items in the collection](#custom-order-of-items-in-the-collection) |
19 | 20 | - [Open-generics](#open-generics)
|
20 | 21 | - [Co-variant generics](#co-variant-generics)
|
21 | 22 | - [Composite Pattern support](#composite-pattern-support)
|
@@ -432,6 +433,46 @@ class Filtering_not_resolved_services
|
432 | 433 | }
|
433 | 434 | ```
|
434 | 435 |
|
| 436 | +#### Custom order of items in the collection wrapper |
| 437 | + |
| 438 | +To achieve the custom ordering we may use the [Meta or Tuple with Metadata](#meta-or-tuple-of-a-with-metadata) wrapper and the [Decorator](Decorator.md) feature. |
| 439 | + |
| 440 | +```cs |
| 441 | +class Collection_with_custom_order |
| 442 | +{ |
| 443 | + public sealed class OrderMetadata // may be an suitable data structure defined by you |
| 444 | + { |
| 445 | + public readonly int Value; |
| 446 | + public OrderMetadata(int value) => Value = value; |
| 447 | + } |
| 448 | + |
| 449 | + // The "decorator" method sorting the `I` collection based on the `OrderMetadata` before returning it. |
| 450 | + static IEnumerable<I> SortByOrderMetadata(IEnumerable<Tuple<I, OrderMetadata>> ii) => |
| 451 | + ii.OrderBy(x => x.Item2.Value).Select(x => x.Item1); |
| 452 | + |
| 453 | + [Test] public void Example() |
| 454 | + { |
| 455 | + var container = new Container(); |
| 456 | + container.Register<I, C>(setup: Setup.With(new OrderMetadata(3))); |
| 457 | + container.Register<I, A>(setup: Setup.With(new OrderMetadata(1))); |
| 458 | + container.Register<I, B>(setup: Setup.With(new OrderMetadata(2))); |
| 459 | + |
| 460 | + container.RegisterDelegate<IEnumerable<Tuple<I, OrderMetadata>>, IEnumerable<I>>(SortByOrderMetadata, setup: Setup.Decorator); |
| 461 | + |
| 462 | + var items = container.Resolve<I[]>(); |
| 463 | + |
| 464 | + Assert.IsInstanceOf<A>(items[0]); |
| 465 | + Assert.IsInstanceOf<B>(items[1]); |
| 466 | + Assert.IsInstanceOf<C>(items[2]); |
| 467 | + } |
| 468 | + interface I {} |
| 469 | + class A : I { } |
| 470 | + class B : I { } |
| 471 | + class C : I { } |
| 472 | +} |
| 473 | +``` |
| 474 | + |
| 475 | + |
435 | 476 | #### Open-generics
|
436 | 477 |
|
437 | 478 | If you registered both closed and open-generic implementation of the service,
|
|
0 commit comments