2016-01-21 38 views
0

我有一個通用接口IDataService<T>及其默認實現DataService<T>。於是,一些類型有其特定的服務接口,實現還IDataService,例如:StructureMap加載默認的通用實現,如果專門不存在

public interface IClientService : IDataService<Client> 
{ 
    void SomeProcess(); 
} 

public class ClientService : DataService<Client>, IClientService 
{ 
    public override SomeDataServiceMethodOverride(); 
    public void SomeProcess(); 
} 

正如你所看到的,ClientService是一家專門IDataService<Client>延伸的DataService<Client>的功能,還實現了另一個接口。

我想那是什麼,當我問到StructureMap一個IDataService<Client>它給了我一個ClientService,但是當我問一個IDataService<OtherEntity>只是回落到默認實現DataService<OtherEntity>。我曾到現在爲止,我StructureMap配置爲:

Scan(
    scan => { 
     scan.AssemblyContainingType<IClientService>(); 
     scan.AssemblyContainingType<ClientService>(); 

     scan.WithDefaultConventions(); 
    }); 
For(typeof(IDataService<>)).Use(typeof(DataService<>)); 

但問題是,要求IDataService<Client>時未實例化一個ClientService,但DataService<Client>。現在我把最後一行改爲:

For(typeof(IDataService<OtherEntity>)).Use(typeof(DataService<OtherEntity>)); 

但是之後我必須爲沒有具體服務實現的實體做這件事。我怎麼能自動做到這一點?

+0

看看 - [文件](http://docs.structuremap.net/Generics.htm) –

+0

在本文檔頁面他們明確地註冊的具體實現,但我不想這樣做,正如我在上次聲明中所說的那樣。 –

+0

你怎麼知道它實例化DataService而不是ClientService.did,你檢查它是否調用你的覆蓋,只是健全性檢查。實際上,您將DataService註冊爲IDataservice的具體內容,這就是您請求時所提供的結構圖。我想你需要再次看看你的繼承鏈。可能必須下去[This route](http://www.mikeobrien.net/blog/registering-types-with-interface-that/) –

回答

1

從您的描述中,您聽起來好像想要註冊具體服務類型上的所有接口。 StructureMap通過提供定義適用於掃描操作的自定義約定的功能來實現此功能。您可以定義一個實現StructureMap.Graph.IRegistrationConvention的類型,然後定義ScanTypes方法。該方法提供了掃描類型的集合以及存儲您的自定義配置的註冊表。

以下代碼段在功能上等同於StructureMap文檔found here中的代碼。

public class AllInterfacesConvention : StructureMap.Graph.IRegistrationConvention 
{ 
    public void ScanTypes(TypeSet types, Registry registry) 
    { 
     foreach(Type type in types.FindTypes(TypeClassification.Concretes | TypeClassification.Closed) 
     { 
      foreach(Type interfaceType in type.GetInterfaces()) 
      { 
       registry.For(interfaceType).Use(type); 
      } 
     } 
    } 
} 

然後,您可以更新掃描操作以應用此約定。

var container = new Container(x => { 
    x.For(typeof(IDataService<>)).Use(typeof(DataService<>)); 

    // Override custom implementations of DataService<> 
    x.Scan(scanner => { 
     scan.AssemblyContainingType<IClientService>(); 
     scan.AssemblyContainingType<ClientService>(); 
     scan.Convention<AllInterfacesConvention>(); 
    }); 
}); 

// This should now be of type ClientService 
var service = container.GetInstance<IDataService<Client>>(); 
+0

感謝你的答案,我結束了使用 'scan.ConnectImplementationsToTypesClosing(typeof(IDataService <>));' –

相關問題