.net - 温莎城堡 : How to specify a constructor parameter from code?

标签 .net castle-windsor

说我有以下类(class)

MyComponent : IMyComponent {
  public MyComponent(int start_at) {...}
}

我可以通过xml向城堡温莎注册它的一个实例,如下所示
<component id="sample"  service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample">  
  <parameters>  
    <start_at>1</start_at >  
  </parameters>  
</component>  

我将如何在代码中做完全相同的事情? (注意,构造函数参数)

最佳答案

编辑:在 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));
        }

    }
}

关于.net - 温莎城堡 : How to specify a constructor parameter from code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/87812/

相关文章:

c# - 为什么 WindsorDependencyResolver 无法解析?

.net - .NET 4.5会引入CLR的新版本吗?

c# - 方法的缓存属性?

.net - SQL Server View 在 Entity Framework 中返回不同的结果

.net - 温莎城堡有什么缺点吗?

caSTLe-windsor - 温莎城堡 : custom processing when starting service

caSTLe-windsor - 温莎城堡 : Can I get all instances of a type?

c# - TPL 数据流向所有消费者重复消息

c# - 数组作为 DataGrid 的数据源 : how to customize columns?

entity-framework - 为什么DbContext每次都在dispose?