2017-04-06 83 views
1

直到最近我用AutoFac其中有方法AsImplementedInterfaces() 這確實StructureMap:註冊爲實現接口,如在AutoFac

註冊類型提供其所有的公共接口作爲服務(不包括IDisposable接口)。

該裝置(例如,服務)我有一些基本接口和用於每concerte服務級

接口請參見下面的簡單的代碼:

public interface IService {} 

public interface IMyService: IService 
{ 
    string Hello(); 
} 

public class MyService: IMyService 
{ 
    public string Hello() 
    { 
     return "Hallo"; 
    } 
} 

// just a dummy class to which IMyService should be injected 
// (at least that's how I'd do it with AutoFac. 
public class MyClass 
{ 
    public MyClass(IMyService myService) { } 
} 

基本上我要注入我的服務界面(可以這麼說)而不是具體的服務。

現在我必須使用StructureMap,但我很難找到我需要的東西。 有AddAllTypesOf<T>但這會註冊具體類型。

這是甚至有可能與StructureMap,如果是的話如何?

回答

0

所以,我找到了答案(S)

1. 首先,你可以使用

public class TestRegistry : Registry 
{ 
    public TestRegistry() 
    { 
     Scan(x => 
     { 
      x.TheCallingAssembly(); 
      x.RegisterConcreteTypesAgainstTheFirstInterface(); 
     }); 
    } 
} 

這將登記每一個具體類針對這可能是過於寬泛的第一界面。

2. 如果是這樣,你可以使用下面的代碼我改編自http://structuremap.github.io/registration/auto-registration-and-conventions/

我不得不將Each()更改爲foreach由於編譯錯誤,並使整個類通用。

public class AllInterfacesConvention<T> : IRegistrationConvention 
{ 
    public void ScanTypes(TypeSet types, Registry registry) 
    { 
     // Only work on concrete types 
     foreach (var type in types.FindTypes(TypeClassification.Concretes | TypeClassification.Closed).Where(x => typeof(T).IsAssignableFrom(x))) 
     { 
      if(type == typeof(NotInheritedClass)) 
      { 
       continue; 
      } 

      // Register against all the interfaces implemented 
      // by this concrete class 
      foreach (var @interface in type.GetInterfaces()) 
      { 
       registry.For(@interface).Use(type); 
      } 
     } 
    } 
} 

如果從鏈接中獲取代碼示例,則將包含每個具體類型。隨着我的變化,僅包含從T繼承的演奏班。

在您的註冊表

你會使用它像

public class TestRegistry : Registry 
{ 
    public TestRegistry() 
    { 
     Scan(x => 
     { 
      x.TheCallingAssembly(); 
      x.Convention<AllInterfacesConvention<YOUR_BASE_INTERFACE>>(); 
     }); 
    } 
} 

注意的structuremap的GetInstance總會解決的具體類不管你以前註冊它們。 請參閱https://stackoverflow.com/a/4807950/885338

相關問題