This project is read-only.

Map two (or more?) interfaces to same service implementation

Nov 16, 2010 at 12:09 PM

I've the following problem for which I have linked a sample app at the end of the post. I have the following dependency structure in this sample app:

MainWindowViewModel -> IAbstraction -> (impl by) Abstraction -> IFoo


I'd like both IFoo and IBar to be implemented by the same class FooBar. Using the DefineService attribute doesn't do the job, even with lifetime specified as Singleton, because (by-design) it uses the "singleton-per-resource-type" approach.

So, a suggestion from Rishi (if I understood it correctly :)) was to register two locator adaptors, one for each IFoo and IBar, which return the same ILocatorAdaptor implementation. This implementation would, in turn, return the same instance of FooBar, guaranteeing in fact it's a per-app singleton.

Maybe someone can see what I'm doing wrong (or maybe it can't be done like this at all and I should implement my custom mapping attribute + resource locator which do the same thing).


File link (sorry for the "re-used" name of the project :D):


Nov 16, 2010 at 12:43 PM
Edited Nov 16, 2010 at 12:49 PM

The problem is simple, in your service declaration you have dependencies on IFoo and IBar types - however you are resolving them using adapters and without registering them with RLF directly, which means nRoute doesn't know about they two types since they are not registered. And given the dependencies have not been resolved, when you ask for IAbstraction it raises an exception. So, the solution is to change:

[assembly: DefineService(typeof(IAbstraction), typeof(Abstraction), typeof(IFoo), typeof(IBar), Lifetime = InstanceLifetime.Singleton)]


[assembly: DefineService(typeof(IAbstraction), typeof(Abstraction), Lifetime = InstanceLifetime.Singleton)]

Just to reiterate, adapters work in a fall-through manner - so when nRoute can't resolve a resource it asks each of the adapters if it can resolve the requested resource, and if so then it delegates the resolution to the adapter. This is a powerful way to bring in outside systems or even others IoCs into the fold - however it bypasses nRoute's native understanding of a resource and hence the exception.

Hope this is clear.

Nov 16, 2010 at 12:51 PM

Thanks for the explanation, it's clear now. I actually already tried NOT declaring the unmapped resources as dependencies, but I had the bit more complicated scenario equivalent of Abstraction depending on another thing which in turn depended on IFoo, But in that "thing"'s mapping I had declared IFoo as a dependency, when in fact as you explained, I shouldn't have :)

Thanks again!