Question

I am trying to configure the NCommon NHRepository in my project with Structure Map. How do I stop it from choosing the greediest constructor?

 public class NHRepository<TEntity> : RepositoryBase<TEntity>
 {

    public NHRepository () {}


    public NHRepository(ISession session)
    {
        _privateSession = session; 
    }

    ...
}

My structure map configuration

ForRequestedType(typeof (IRepository<>))
                .TheDefaultIsConcreteType(typeof(NHRepository<>))

Cheers Jake

Was it helpful?

Solution

You can set the [DefaultConstructor] Attribute for the constructor you wish as a default. In your case, setting it on the NHRepository() constructor would make it the default constuctor for StructureMap to initialize.

Update: well, in the latest version of StructureMap, using .NET 3.5 you can also specify it using the SelectConstructor method:

var container = new Container(x =>
{
  x.SelectConstructor<NHRepository>(()=>new NHRepository());
});

Finally, I'm sure you would be able to define it in the XML configuration of StructureMap, but I haven't used that. You could do a little search on it. For more information on the above method, see: http://structuremap.sourceforge.net/ConstructorAndSetterInjection.htm#section3

OTHER TIPS

So +1 for Razzie because this would work if the NHRepository was in my own assembly, instead I choose to wrap the NHRepository with my own Repository like below..

public class Repository<T> : NHRepository<T>
{
    [DefaultConstructor]
    public Repository()
    {

    }

    public Repository(ISession session)
    {

    }
}

ForRequestedType(typeof (IRepository<>))
                .TheDefaultIsConcreteType(typeof (Repository<>));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top