Determine if a given type can currently be resolved by a Castle Windsor container
I have a scenario where I need to know 开发者_StackOverflow社区if a specific type can currently be resolved by a Windsor container. The wrinkle is that this type has dependencies. So I have a ProductRepository
class that implements IRefDataRepository
and depends on IProductDataProvider
. I need to know if I can successfully resolve IRefDataRepository
from the container.
I tried using IKernel.HasComponent(typeof(IRefDataRepository))
IKernel.GetAssignableHandlers(typeof(IRefDataRepository))
both of which return ProductRepository
even there is no IProductDataProvider
registered. (So IWindsorContainer.Resolve(typeof(IRefDataRepository))
will throw)
My current solution is to write an extension method that actually tries to resolve the type (via IWindsorContainer.Resolve(IRefDataRepository)
), catches the exception, and returns true if the type resolves and false otherwise. But I'm wondering if there is a better way.
You're doing it wrong.
You should have divided your program into two explicit parts:
- setup
- actual code
You register things in setup, then run the actual code where you can resolve stuff. If you can't resolve it, you have a bug in your setup code.
The 2nd part of the code should have no knowledge of the container, and polling the container is a big code smell.
Now, having said that, when you absolutely have to do it for some reason, get a handler for the component you need, and check it's state (handler.CurrentState
). If it's Valid
your component is safe to be resolved. Opposite does not have to be true though!
精彩评论