[英]StructureMap: Wiring (generic) implementations to an implementation of another type
如果我有一個界面:
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<Account>
而不會因其他界面/配置而使項目混亂不堪。
StructureMap的掃描功能可以處理以下問題:
ObjectFactory.Initialize(x => {
x.Scan(y =>
{
y.TheCallingAssembly();
y.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
});
});
使用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的源代碼版本才能進行編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.