views:

354

answers:

3

Is there a way to replace the call to Activator.CreateInstance() used inside NHibernate 2.0.1GA to construct the entities? Ideally I'd like to replace it with StructureMap.ObjectFactory.GetInstance().

+4  A: 

You can't do this easily with constructor injection. The NHibernate internals may need to create a proxy object inherited from your domain class with Lazy loading code etc. sprinkled in there, so, as far as I know, there's no simple option to override the construction of your object.

You can get dependency injection working with NHibernate fairly easily though, by writing an interceptor that will build up the object for you via property setter injection. There is an example of this here. That example is using Windsor as the DI container, but you can do the same thing with StructureMap of course - here are the relevant docs for StructureMap - look for the section on "Applying Setter Injection to an Existing Object (BuildUp)".

Caveat: injecting dependencies into your domain model is often seen as a symptom of a design problem, and many people avoid doing this, so be sure this is really what you want to do before you start coding it!

Steve Willcock
Constructor injection is possible
Paco
I didn't say it wasn't possible I said it wasn't easy. If I'm wrong, please enlighten me :)
Steve Willcock
Then I'm not reading well. Sorry.
Paco
I 100% agree that this is something that should not normally be done, but I have a fragmented data layer (outside my control) and I'd like to use IoC so I can mock the other half and vice-versa. If there is a better way to handle that, I'd love to hear it.
Jeff Mc
+1  A: 

You can do setterinjetion by implementing IInterceptor and doing the injection in the onload method with Objectfactory.BuildUp. This is easy to implement, setter injection might not be what you want.

You can do constructor injection by implementing your own IBytecodeProvider and ReflectionOptimizer. This is a little harder to do, but it is possible!

I don't recommend to inject things in entities. In 99.9% of the cases this will lead to bad design and make layering in your design impossible. Maybe you facing the 0.01% of the cases where it is the right thing to do. It's something you do as frequently as typing goto statements.

Paco
+2  A: 

Take a look at this post from Fabio Maulo (current NHibernate lead dev), he solved this some months ago. The code is for NHibernate 2.1 but I think it could be backported to 2.0.1GA by removing the IProxyFactoryFactory parts.

Mauricio Scheffer