简体   繁体   中英

StructureMap: Wiring (generic) implementations to an implementation of another type

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 (eg AccountRepository, ContactRepository, etc.), what's the best way to to use StructureMap (2.5.3) to generically wire them all up?

eg, 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.

StructureMap's scanning feature can handle that:

ObjectFactory.Initialize(x => {
  x.Scan(y =>
  {
      y.TheCallingAssembly();
      y.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
    });
});

Using Fasterflect you could write the following code:

// get the assembly containing the repos
var assembly = Assembly.GetExecutingAssembly();
// get all repository types (classes whose name end with "Repository")
var types = assembly.Types( Flags.PartialNameMatch, "Repository" ).Where( t => t.IsClass );
// configure StructureMap for the found repos
foreach( Type repoType in types )
{
    Type entityType = assembly.Type( repoType.Name.Replace( "Repository", "" );
    // define the generic interface-based type to associate with the concrete repo type
    Type genericRepoType = typeof(IRepository).MakeGenericType( entityType );
    ObjectFactory.Configure( x => x.For( RequestedType( genericRepoType ) ).Use( repoType ) );
}

Note that the above is written from memory and has not been compiler verified. You'll need the source version of Fasterflect to make it compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM