【问题标题】:StructureMap: Wiring (generic) implementations to an implementation of another typeStructureMap:将(通用)实现连接到另一种类型的实现
【发布时间】:2010-05-14 16:22:49
【问题描述】:

如果我有接口:

public interface IRepository<T>

还有一个抽象类:

public abstract class LinqToSqlRepository<T, TContext> : IRepository<T>
        where T : class
        where TContext : DataContext

还有一大堆 IRepository / LinqToSqlRepository 的实现(例如 AccountRepository、ContactRepository 等),使用 StructureMap (2.5.3) 将它们全部连接起来的最佳方法是什么?

例如,我希望这段代码通过:

[Test]    
public void ShouldWireUpAccountRepositories
{
  var accountRepo = ObjectFactory.GetInstance<IRepository<Account>>();
  Assert.IsInstanceOf<AccountRepository>(accountRepo);
}

没有明确写这个:

ObjectFactory.Configure(x => x.ForRequestedType<IRepository<Account>>()
    .TheDefaultIsConcreteType<AccountRepository>());

过去,我们总是在每个存储库上创建一个从通用存储库继承的特定接口,并使用默认扫描程序自动连接所有这些实例,但我希望能够专门要求一个IRepository&lt;Account&gt;,而不用额外的接口/配置使项目混乱。

【问题讨论】:

    标签: c# .net structuremap


    【解决方案1】:

    StructureMap 的扫描功能可以处理:

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

    【讨论】:

      【解决方案2】:

      使用Fasterflect,您可以编写以下代码:

      // 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 ) );
      }
      

      请注意,以上内容是从内存中写入的,尚未经过编译器验证。您需要 Fasterflect 的源代码版本才能编译。

      【讨论】:

      • 1) 你永远不会检查 repoType 是否实现了 genericRepoType。 2) 如果你能提供帮助,你不应该在循环中调用 ObjectFactory.Configure()。 StructureMap 的 Scan() 和 IRegistrationConvention 功能就是为此目的而设计的。
      猜你喜欢
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2011-01-22
      • 1970-01-01
      相关资源
      最近更新 更多