views:

477

answers:

2

I've read somewhere that NHibernate 2.1 supports constructor dependency injection for it's entites.

How do I go about configuring StructureMap and NHibnerate 2.1 to get this up and running ?

A: 

By setting up StructureMap across all of your entities (classes etc) and then using the interface for each of those as the signature for the constructor of a class...when you instantiate the class that has a dependency in its constructor StructureMap will auto inject it for you!

[PluginFamily("Default")]
public interface IWidget1

[Pluggable("Default")]
public class Widget1 : IWidget1

[PluginFamily("Default")]
public interface IAnotherWidget

[Pluggable("Default")]
public class AnotherWidget : IAnotherWidget
{
    public AnotherWidget(IWidget widget)
    {
       ...
    }
}

IAnotherWidget _anotherWidget = ObjectFactory.GetInstance<IAnotherWidget>();

Something like that!

This may be of use too: http://stackoverflow.com/questions/752761/can-i-replace-the-call-to-activator-createinstance-in-nhibernate/753221

And this: http://devlicio.us/blogs/billy_mccafferty/archive/2007/02/05/inject-di-container-into-domain-objects-with-nhibernate.aspx

Andrew Siemer
+2  A: 

I realize this is an old question, but in case it might be useful.

EDIT: Original posted links weren't effective for NHib 2.1, found better info.

For NHibernate 2.1, you can create an Interceptor and override the Instantiate method and have your container create your instances there. Here is an example

If you wanted to do property injection instead, you can use the same technique but do your work in the onLoad method instead.

Remi Despres-Smyth