Few months ago, a user asked the following question on the Castle users discussion group. A friend asked me about the same thing today, so I thought I’d blog this so that’s easier to find than the discussion group thread. Anyway, here’s the question:
say I have the following types
Is there a way to register ISomeType<> in the container so that for the general case it uses SomeTypeImpl<> but for cases where T is ISomeSpecificSpecifier it could use SomeSpecificTypeImpl<>?
Solution take one – the explicit version
The solution may be similar to the following sketchy code.
This version contains an explicit extension to the component registration API, to specify which component you prefer in which case. It also uses and IHandlerSelector implementation to do the actual work during resolution. It is possible however to not extend the API, and use the information we already have
Solution take two – the implicit version
This version relies on the information provided in component’s generic type constraints. The Registration API is not extended, and we just do a little bit more work in the selector. Is this version better? It depends. The explicit version is… well – explicit about what it does, and for which components. The implicit one works on its own and if you’re not careful you may end up chasing very strange bugs in your code. That said, if you do go for the second option, be sure to at least add some diagnostics logging to it, so that you can see what it does when you’re not watching.