Castle Windsor: How to specify a constructor parameter from code?

前端 未结 6 489
轻奢々
轻奢々 2020-12-30 08:34

Say I have the following class

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

I can register an instance of it wit

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 09:07

    You can use the AddComponentWithProperties method of the IWindsorContainer interface to register a service with extended properties.

    Below is a 'working' sample of doing this with an NUnit Unit Test.

    namespace WindsorSample
    {
        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();
                IDictionary parameters = new Hashtable {{"start_at", 1}};
    
                container.AddComponentWithProperties("concrete", typeof(IMyComponent), typeof(MyComponent), parameters);
    
                IMyComponent resolvedComp = container.Resolve();
    
                Assert.That(resolvedComp.Value, Is.EqualTo(1));
            }
    
        }
    }
    

提交回复
热议问题