Castle Windsor - how to resolve components based on constructor parameters

我是研究僧i 提交于 2019-12-04 03:48:52

Normally this is done at registration-time, not at resolution-time. In fact, calling Resolve() in your code should be rare since you're using the container as a service locator.

container.Register(
   Component.For<MyComponent>()
            .Named("comp_a")
            .DependsOn(new { name = "a" }),
   Component.For<MyComponent>()
            .Named("comp_b")
            .DependsOn(new { name = "b" }));

var a1 = container.Resolve<MyComponent>("comp_a");
var a2 = container.Resolve<MyComponent>("comp_a");
var b = container.Resolve<MyComponent>("comp_b");
Assert.AreSame(a1, a2);
Assert.AreNotSame(a1, b);

Instead of using Resolve() as in my code (which is purely for testing purposes) you normally use service overrides or a handler selector to select which MyComponent to inject into your other services.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!