温莎城堡-如何基于构造函数参数解析组件 [英] Castle Windsor - how to resolve components based on constructor parameters

查看:58
本文介绍了温莎城堡-如何基于构造函数参数解析组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个像这样的组件

Say I have a component like this

public class MyComponent
{
    public MyComponent(string name)
    {
    }
}

我基本上是想使提供的构造函数参数在解析时作为组件标识符的一部分。如果您从未使用那组参数来解析它,它将实例化一个新参数。

I basically want to have the provided constructor parameters behave as part of the component identifier when resolving it. If you've never resolved it with that set of parameters, it will instantiate a new one.

换句话说,我想以某种方式修改以下测试以使其成功:

In other words, I want to somehow modify the following test to succeed:

IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<MyComponent>());
MyComponent a1 = container.Resolve<MyComponent>(new { name = "a" });
MyComponent a2 = container.Resolve<MyComponent>(new { name = "a" });
MyComponent b = container.Resolve<MyComponent>(new { name = "b" });

Assert.AreSame(a1, a2);
Assert.AreNotSame(a1, b);

当前失败,因为它将实例化为name = a,然后为所有将来的名称返回相同的对象= a和name = b。

Currently it fails because it will instantiate with name=a, then return the same object for all future name=a and name=b.

谢谢!

推荐答案

通常这是在注册时完成的,而不是在解决时完成的。实际上,在代码中很少调用Resolve(),因为您将容器用作服务定位器。

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);

而不是像我的代码中那样使用Resolve()(仅用于测试目的)服务重写或处理程序选择器选择要注入到其他服务中的MyComponent。

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.

这篇关于温莎城堡-如何基于构造函数参数解析组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆