Search code examples
c#dependency-injectioncastle-windsor

Castle Windsor Dependency Injection - restore dependencies for existing instance


I have a fairly straight-forward scenario that I am trying to solve but I'm hitting a few brick walls with Windsor - perhaps I'm trying to solve the problem in wrong way?

I have a type called Foo as follows:

public class Foo
{
    [NonSerialized]
    private IBar bar;

    public IBar Bar
    {
        get { return this.bar; }
        set { this.bar = value; }
    }

    public Foo(IBar bar)
    {
    }
}

I instantiate via the container in the normal way:

var myFoo = container.Resolve<Foo>();

The dependency IBar is registered with the container and gets resolved when the object is created. Now that the type has been created, I need to serialize it and I don't want to serialize IBar so it's marked with a NonSerialized attribute.

I then need to deserialize the object and return it to it's former state. How do I achieve this with Castle Windsor? I already have an instance, it is just missing it's dependencies.

If I was using Unity, I would use BuildUp() to solve the problem, but I want to use Castle Windsor in this case.


Solution

  • It seems like Foo is having multiple concerns. Try to separate the data part from the behavior by creating a new class for the data and use it as a property in the Foo class:

    [Serializable]
    public class FooData
    {
    }
    
    public class Foo
    {
        private FooData data = new FooData();
    
        public IBar Bar { get; private set; }
    
        public FooData Data { get; set; }
    
        public Foo(IBar bar)
        {
        }
    }
    

    When you have this construct in place you can deserialize FooData and use it in a created Foo:

    var foo = container.Get<Foo>();
    foo.Data = DeserializeData();