I have a generic IRepository that has 2 constructors, one have none parameters, other has the datacontext as parameter. I want to define to structuremap to aways in this case use the parameterless constructor. I want a way to create a parameterless contructor, other solutions that I have seen, they create a new Datacontext and pass it to the constructor that has parameters.
Asked
Active
Viewed 842 times
6
-
Does this help you? http://stackoverflow.com/questions/289512/structuremap-how-to-define-default-constructor-by-code – uvita May 03 '10 at 16:56
-
Does not becaouse I'm using a generic repository! I need to do something like this: x.SelectConstructor(IRepository
....... – Diego Correa May 03 '10 at 17:07 -
That doesn't make sense. Interfaces do not have constructors. – Joshua Flanagan May 03 '10 at 17:37
-
Sorry my mistake: It should look like this: x.SelectConstructor
>(()=> new Repository – Ricky May 03 '10 at 17:52()); but this does not work...any way to make this work? -
Why do you want a parameterless constructor? The whole point of DI is that the container will provide the concrete implementation of the interface parameters on your constructor. – Rob West May 05 '10 at 10:04
1 Answers
4
By default, StructureMap will use the constructor with the most arguments. In your case, since you want it to use the parameterless constructor, use the DefaultConstructorAttribute
:
[DefaultConstructor]
public void Repository<T>() { }
public void Repository<T>(DataContext dataContext) { }

Michael Hedgpeth
- 7,732
- 10
- 47
- 66
-
Is it possible to do this in any other way? It would appear, without access/desire to add an attrbiute to your class you can't specify a default constructor for open generic types because you can't formulate a constructor expression with them. – Cargowire Jul 15 '11 at 13:55
-
You can configure StructureMap to call the other constructor explicitly, too. If I couldn't modify the class in question that's the approach I would take. – Michael Hedgpeth Jul 18 '11 at 15:37
-
But you can't actually call the constructor of an open generic e.g. BaseClass
etc because you can't compile an expression that doesn't fulfill those parameters. – Cargowire Jul 18 '11 at 20:36