Castle Windsor Dependency Injection - restore dependencies for existing instance
Asked Answered
E

1

1

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.

Elmer answered 8/11, 2010 at 20:24 Comment(0)
N
2

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();
Nickinickie answered 8/11, 2010 at 20:43 Comment(7)
There is no FooData, there is only Bar. Bar can't be serialized. Bar doesn't even need to be exposed but it must be restored when the object is deserialized.Elmer
There is no FooData yet. But you are going to create it; that's what I'm saying ;-)Nickinickie
I'm not following you! IBar is probably a repository which Foo uses to load/save data. How doe I get my repository, or Bar, back into Foo post-deserialize?Elmer
@Steve: If you look at the last two lines of code in my answer, you see that Foo never gets serialized. You retrieve a new instance of Foo from the container and assign a deserialized FooData to it. If that doesn't work for you, please update your question with some more information. I bet that object is not called Foo but something like ShipOrderCommand?Nickinickie
You are correct, Foo is something like an Order business object and Bar is an OrderRepository. I need to serialize/deserialize the stateful Order information, and then restore stateless dependencies such as repositories.Elmer
The FAQ: stw.castleproject.org/…Amerind
That's very clear - Windsor does not inject dependencies into existing instances.Elmer

© 2022 - 2024 — McMap. All rights reserved.