2017-04-06 59 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