温莎城堡依赖注入 - 还原现有实例的依赖 [英] Castle Windsor Dependency Injection - restore dependencies for existing instance

查看:233
本文介绍了温莎城堡依赖注入 - 还原现有实例的依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我试图解决,但我击中温莎几个砖墙一个相当直接的场景 - 也许我试图解决错误的方式问题

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?

我有一个名为Foo的类型如下:

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.

推荐答案

看起来是有多的关注。尝试通过创建数据的新类从行为的数据部分分开,并用它作为类的属性:

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)
    {
    }
}

当你在的地方有这样的结构,你可以反序列化 FooData ,并在创建的

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

这篇关于温莎城堡依赖注入 - 还原现有实例的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆