开发者

Can I get Castle Windsor to complain when I try to Resolve a single component which is multiply registered?

开发者 https://www.devze.com 2023-03-02 01:10 出处:网络
If I register two components for the same service, e.g. container.Register( Component.For<IThing>.ImplementedBy<Thing1>(),

If I register two components for the same service, e.g.

container.Register(
    Component.For<IThing>.ImplementedBy<Thing1>(),
    Component.For<IThing>.ImplementedBy<Thing2>())

I find it surprising that if I Resolve a dependency on IThing or ask it to be resolved manually, Windsor will simply pick one to give me (the first, or Thing1, it appears).

I understand this might be beneficial in some cases to allow one registrar to "override" another by getting first in the list of registered components.

Is there a way to 开发者_开发知识库specify that when the IThing service is resolved singly that an exception should be thrown in this case?


Yes, Windsor will by default use the first component as default for any given service and it not throwing but working like that is a really powerful feature used in some advanced scenarios like decorators, of chain of responsibility pattern.

What would be your reason to throw in those cases?

Anyway, if you're really confident that's what you want, I'd write a test that grabs all handlers from the container

container.Kernel.GetAssignableHandlers(typeof(object))

And then you can inspect them and see if any Service is exposed by more than a single handler and act accordingly.


You can create an implementation of IHandlerSelector that has an opinion about resolving IThings, throwing if more than one handler is available for your IThing service.

You can read more about handler selectors here.

The handler selector could be registered during development only to avoid anything going more wrong than necessary in production :)

Another strategy, which is one I usually follow, is to create a couple of automated tests that load the container in all possibly configurations (environment/customer), and then do a couple of assertions on it.

Assuming your container is fully loaded, something like

Assert.That(container.ResolveAll<IThing>(), Has.Length.EqualTo(1));

would suffice.

0

精彩评论

暂无评论...
验证码 换一张
取 消