温莎城堡IoC属性注入。在ChildClass构造函数中使用BaseClass的属性 [英] Castle Windsor IoC property injection. Using property from BaseClass inside ChildClass constructor

查看:102
本文介绍了温莎城堡IoC属性注入。在ChildClass构造函数中使用BaseClass的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下基类

public class BaseClass
{ 
    public ISomeObject Property { get; set; } 
}

和从ClassClass继承的ChildClass。我需要在ChildClass中使用BaseClass的Property构造函数,但我没有根据需要由IoC初始化,并且其值为null。如果我在ChildClass的方法中使用它,则会初始化Property。
我在做什么错了?

and ChildClass inherited from BaseClass.I need to use Property from BaseClass inside ChildClass constructor, but it's not initialized by IoC as I want and has value null. And if I use it inside ChildClass's methods, Property is initialized. What am I doing wrong?

这是我在IoC容器中注册ISomeObject的方式

Here is how I register ISomeObject in IoC container

container.Register(
Component.For<ISomeObject>()
.ImplementedBy<WebSomeObject>().LifestyleSingleton());


推荐答案

温莎城堡不是问题,但.NET的工作方式。构造函数作为.NET框架的一部分运行,实例化一个类的新实例。只有在构造完成之后,其他代码(例如Windsor)才能在其上设置属性或执行方法。

This is not an issue with Castle Windsor but of the way .NET works. The constructor is run as part of the .NET framework instantiating a new instance of a class. Only after construction completes can other code (like Windsor) set properties on it or execute methods.

如果要属性要在子类构造函数中可用,则需要将其作为参数添加到 BaseClass 构造函数中,并在子类上设置匹配的构造函数。

If you want Property to be available inside the the child class constructor, then you need to add it as a parameter to the BaseClass constructor and set up a matching constructor on your child class.

这篇关于温莎城堡IoC属性注入。在ChildClass构造函数中使用BaseClass的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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