Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve registration order for IEnumerable #288

Closed
seesharper opened this issue Jun 28, 2016 · 4 comments
Closed

Preserve registration order for IEnumerable #288

seesharper opened this issue Jun 28, 2016 · 4 comments

Comments

@seesharper
Copy link
Owner

No description provided.

@seesharper
Copy link
Owner Author

@bounav
Copy link

bounav commented Jan 30, 2017

I'm using the chain of responsibility pattern and I have to resolve my interface as an IEnumerable<T> in a specific sequence.

I've been reading seesharper/LightInject.Microsoft.DependencyInjection#3 and the related issues and I'm left confused...

The behaviour I get in my unit tests is that LightInject does not resolve a type with multiple implementations in the order the implementations were registered. Any reason why?

container.Register<IFoo, One>();
container.Register<IFoo, Two>("Two");
container.Register<IFoo, Three>("Three");
container.Register<IFoo, Four>("Four");

// foos will contain IFoo implementations that are not ordered in this sequence: One, Two, Three, Four
var foos = container.GetAllInstances<IFoo>();

In order to get the instances ordered in a given sequence, I ended up doing registering IEnumerable<IFoo> explicitly:

container.Register<One>();
container.Register<Two>();
container.Register<Three>();
container.Register<Four>();

container.Register<IEnumerable<IFoo>>(f => new IFoo[] { 
    f.GetInstance<One>(), 
    f.GetInstance<Two>(),
    f.GetInstance<Three>(),
    f.GetInstance<Four>()
});

// foos contains instances in the following order: One, Two, Three, Four
var foos = container.GetAllInstances<IFoo>();

Is this the the recommended way of making an IEnumerable<T> resolve in a deterministic fashion?

@seesharper
Copy link
Owner Author

The reason that this is not deterministic is that registrations are stored in a hash table which does not preserve the order. Items in an hash table ends up in buckets based on hash code and hence the order is lost.

Your solution would work perfectly.

@Mike-E-angelo
Copy link

Bummer. This would be useful for scenarios where the number of items are arbitrary and are added without knowing the types added before or after them, but where order is important. Would it be possible to consider using a SortedDictionary instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants