问题
I have a base class as following
public class BaseClass
{
public ISomeObject Property { get; set; }
}
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?
Here is how I register ISomeObject in IoC container
container.Register(
Component.For<ISomeObject>()
.ImplementedBy<WebSomeObject>().LifestyleSingleton());
回答1:
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.
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.
来源:https://stackoverflow.com/questions/20427882/castle-windsor-ioc-property-injection-using-property-from-baseclass-inside-chil