I have created a class which inherit from the Registry class. In this class I want to inject a property:
ForConcreteType<Person>()
.Configure
.Setter(s => s.PersonSpecializationManager)
.Is(t => t.GetInstance<IPersonSpecializationManager>());
The property definition is as follows:
/// <summary>
/// Gets or sets the person specialization manager
/// </summary>
public virtual IPersonSpecializationManager PersonSpecializationManager
{
get
{
return _personSpecializationManager;
}
set
{
_personSpecializationManager = value;
}
}
I can’t use constructor injection, because the Person is created by NHibernate. And since NHibernate requires an empty constructor, I am forced to do it this way. I am aware of the fact that I could introduce another class which handles the _personSpecializationManager stuff, but I can’t do that.
The above class which inherit from the Registry class is configured in StructureMap. When I place a breakpoint at the line ForConcreteType<Person>() ..., the breakpoint is hit. So I know it should be processed by StructureMap.
So, my question is, why isn’t StructureMap injection my property?
Let me stress on an extremely important part of your sentence containing the answer to your question:
So StructureMap has absolutely no control over the instantiation of this class. So you can’t possibly expect any injection to happen in this class. If you want to do some injection in your NHibernate entities you will have to find out a way (can’t remember from the tip of my head) to take control over the instantiation of them. IIRC this was possible by subscribing to some events in NHibernate. So inside the fictional OnCreated event you could do injection. But once again it will be fake injection because you should now query StructureMap to retrieve the instance of this Person. It’s what people usually refer to as Locator Pattern. And which is considered as an
Anti-Pattern.