NeilD
NeilD

Reputation: 2298

StructureMap and Generics - How do I specify a default constructor?

I have a generic interface:

public interface IRepository<T> { ... }

I have an implementation like this:

public class Repository<T> {
    public Repository<T>() { ... }
}

StructureMap (v 2.6.3) is configured like this:

For(typeof(IRepository<>)).Use(typeof(Repository<>));

When I try and pull an IRepository<Something> out of StructureMap, I get a Repository<Something> as expected. Hooray!

Now I've added a second constructor, and the implementation looks like this:

public class Repository<T> {
    public Repository<T>() { ... }
    public Repository<T>(string database) { ... }
} 

When I try and get an IRepository<Something> now, I get an exception because it defaults to trying to use the new constructor with the parameter. Boo!

How can I change my StructureMap configuration so that it knows to use the parameter-less constructor?

Upvotes: 3

Views: 1465

Answers (1)

Rob West
Rob West

Reputation: 5241

You can achieve this by marking the constructor you want StructureMap to use with the [DefaultConstructor] attribute. As you can see on the StructureMap documentation, it is greedy by default.

Upvotes: 5

Related Questions