问题描述
说我有下面的类
MyComponent : IMyComponent {
public MyComponent(int start_at) {...}
}
我可以通过XML如下城堡温莎注册它的一个实例
I can register an instance of it with castle windsor via xml as follows
<component id="sample" service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample">
<parameters>
<start_at>1</start_at >
</parameters>
</component>
我怎么会去这样做同样的事情,但在code? (请注意,构造函数参数)
How would I go about doing the exact same thing but in code? (Notice, the constructor parameter)
推荐答案
编辑:用流利的接口中使用以下code答案:)
Used the answers below code with the Fluent Interface :)
namespace WindsorSample
{
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
public class MyComponent : IMyComponent
{
public MyComponent(int start_at)
{
this.Value = start_at;
}
public int Value { get; private set; }
}
public interface IMyComponent
{
int Value { get; }
}
[TestFixture]
public class ConcreteImplFixture
{
[Test]
void ResolvingConcreteImplShouldInitialiseValue()
{
IWindsorContainer container = new WindsorContainer();
container.Register(
Component.For<IMyComponent>()
.ImplementedBy<MyComponent>()
.Parameters(Parameter.ForKey("start_at").Eq("1")));
Assert.That(container.Resolve<IMyComponent>().Value, Is.EqualTo(1));
}
}
}