Castle Windsor Dependency Injection - restore dependencies for existing instance

好久不见. 提交于 2019-12-08 06:15:11

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/4127724/castle-windsor-dependency-injection-restore-dependencies-for-existing-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!