Programmatically prioritize IDependency

Topics: Writing modules
Dec 20, 2011 at 7:36 PM
Edited Dec 20, 2011 at 7:36 PM

Let's say there are three classes implementing an IDependency derivative, IMyDependency. Is there a way to somehow programmatically change which one will get instantiated when injecting IMyDependency in the constructor?

Practically such an effect can be achieved with the pattern that's used with body flavors: inject a collection of IHtmlFilters, run all and they will decide to modify the content or not. Also a kind of service locator could be used that also takes a dependency on such a collection but with a method returns the want that is wanted.

I'm curious, how would you do that?

Dec 20, 2011 at 7:43 PM

You can inject an IEnumerable<IMyDependency>. Would that work?

Dec 20, 2011 at 9:04 PM

It would indeed, thanks, that's what I've also meant with IHtmlFilters. I think I'll just do that.

Feb 1, 2012 at 7:55 PM

I have “common” interface in one module IMyService:IDependency and three other modules with implementation classes.

At the end I’m using IEnumerable<IMyService> to get all implementations in yet another module

The problem is that I’m getting multiple times the same implementations. IEnumerable has five elements where I’m expecting three.

Any suggestions?


Feb 1, 2012 at 8:16 PM

That shouldn't happen, must be something strange about how you've implemented them.

Firstly you need to debug and inspect the IEnumerable and see exactly what those five instances are. Actually are you sure there are three elements in there? Sometimes IEnumerable reports an internal size that's higher than the actual number of non-null elements.

Feb 2, 2012 at 3:56 PM

OK, looks like this is not DI, or interface implementation, but other problem which I was ignoring for some time.

Some of my modules are visible twice in Dashboard, and if they are twice enabled, interfaces from them are injected twice. ;)

Feb 2, 2012 at 4:25 PM

Aha :) Maybe it's an error in a Module.txt. Actually I have a few strange artefacts in my dashboard I haven't managed to track down yet; e.g. a feature apparently called "Category" with no description...