views:

46

answers:

1

I have a scenario where I need to know 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.

A: 

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!

Krzysztof Koźmic
This works for the posted scenario, but it doesn't work if I'm using a factory method that takes an argument. handler.CurrentState is valid, but it still can't resolve as the factory method can't get the argument it needs.
Mike Sackton
I would also say that all of this code is the setup side of an ASP.NET MVC application. I'm using a custom controller factory so that I can use Windsor to resolve controller dependencies, and I want to know which controllers will succeed and which won't up front, so I can control which routes to register. I don't want to give access to controllers that won't work.
Mike Sackton
You're doing it wrong then. You should test to make sure **all** your controllers are properly configured and available as you register them. You want to workaround an issue in your code instead of fixing it.
Krzysztof Koźmic