Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure Map - I dont want to use the greediest constructor!

Tags:

structuremap

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

like image 466
superlogical Avatar asked Jul 02 '09 11:07

superlogical


2 Answers

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

like image 64
Razzie Avatar answered Nov 15 '22 10:11

Razzie


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<>));
like image 21
superlogical Avatar answered Nov 15 '22 10:11

superlogical