StructureMap: Wiring (generic) implementations to an implementation of another type
- by Jeremy Frey
If I have an interface:
public interface IRepository<T>
And an abstract class:
public abstract class LinqToSqlRepository<T, TContext> : IRepository<T>
where T : class
where TContext : DataContext
And a whole bunch of implementations of IRepository / LinqToSqlRepository (e.g. AccountRepository, ContactRepository, etc.), what's the best way to to use StructureMap (2.5.3) to generically wire them all up?
e.g., I want this code to pass:
[Test]
public void ShouldWireUpAccountRepositories
{
var accountRepo = ObjectFactory.GetInstance<IRepository<Account>>();
Assert.IsInstanceOf<AccountRepository>(accountRepo);
}
Without explicitly writing this:
ObjectFactory.Configure(x => x.ForRequestedType<IRepository<Account>>()
.TheDefaultIsConcreteType<AccountRepository>());
In the past, we've always created a specific interface on each repository that inherited from the generic one, and used the default scanner to automatically wire all of those instances, but I'd like to be able to ask specifically for an IRepository<Account> without cluttering up the project with additional interfaces / configurations.