Question

I have a component with a property I'd like to override under certain circumstances.
Short version is--

public interface IMyClass
{
  public string SomeValue {get; }
}

public class MyClass : IMyClass
{
   public string SomeValue {get; set;}

   public MyClass()
   {
     //do nothing related to SomeValue
   }

   public MyClass(IHelper helper)
   {
      SomeValue = helper.ReadFromAConfigurationFile();
      //other code follows, unrelated to SomeValue
   }
}

Later on, as suggested here I do..

var classParams= new Dictionary<string, string> { { "SomeValue", "A New Value" } }

    Component.For<IMyClass>()
        .ImplementedBy<MyClass>()
        .DependsOn(classParams)
        .Named("NamedInstanceGoesHere")
        .LifestyleTransient());

Finally, I resolve my component like this:

var myComponent= container.Resolve<IMyClass>("NamedInstanceGoesHere");

When I examine myComponent, the value of SomeValue is as it was set in the constructor and not as I tried to override it.

Is there a way to do what I'm after? Why IMyClass doesn't have a public setter for SomeValue and MyClass does I'm not sure, but it's probably contributing to my problem...

Was it helpful?

Solution

I tried the code below, which executes fine without triggering the assertion. Even with IHelper registered. To me it seems you are probably doing something slightly different.

Good luck,

Marwijn.

using System.Collections.Generic;
using System.Diagnostics;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace ConsoleApplication1
{
    public class IHelper
    {

    }

    public interface IMyClass
    {
        string SomeValue { get; }
    }

    public class MyClass : IMyClass
    {
        public string SomeValue { get; set; }

        public MyClass()
        {
            //do nothing related to SomeValue
        }

        public MyClass(IHelper helper)
        {
            SomeValue = "hello";
        }
    }

    class Program
    {
        static void Main()
        {

            var container = new WindsorContainer();

            var classParams = new Dictionary<string, string> { { "SomeValue", "A New Value" } };

            container.Register(
              Component.For<IHelper>(),
              Component.For<IMyClass>()
                .ImplementedBy<MyClass>()
                .DependsOn(classParams)
                .Named("NamedInstanceGoesHere")
                .LifestyleTransient());

            var myObject = container.Resolve<IMyClass>("NamedInstanceGoesHere");

            Debug.Assert(myObject.SomeValue == classParams["SomeValue"]);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top