Structuremap 结构图通用类型扫描器

Structuremap 结构图通用类型扫描器,structuremap,Structuremap,高级别 使用StructureMap,我可以定义一个程序集扫描规则吗?对于接口IRequestService,它将返回名为TRequestService的对象 示例: 当请求IRequestService时,将注入FooRequestService 当请求IRequestService时,将注入BarRequestService 详细信息 我定义了一个通用接口 public interface IRequestService<T> where T : Request {

高级别

使用StructureMap,我可以定义一个程序集扫描规则吗?对于接口
IRequestService
,它将返回名为TRequestService的对象

示例:

  • 当请求
    IRequestService
    时,将注入
    FooRequestService
  • 当请求
    IRequestService
    时,将注入
    BarRequestService
详细信息

我定义了一个通用接口

public interface IRequestService<T> where T : Request
{
    Response TransformRequest(T request, User current);
}
现在为了解决我的问题,我实现了一个空接口,而不是让
FooRequestService
实现通用接口,而是让它实现这个空接口

public class FooRequestService : IRequestService<Foo>
{
    public Response TransformRequest(Foo request, User current) { ... }
}

public class BarRequestService : IRequestService<Bar>
{
    public Response TransformRequest(Bar request, User current) { ... }
}
public interface IFooRequestService : IRequestService<Foo> { }
如何使用StructureMap的程序集扫描程序创建一个规则,将所有名为TRequestService的对象注册到
IRequestService
(其中T=“Foo”、“Bar”等),以便不必创建这些空接口定义

为了在混合中加入其他内容,我正在处理StructureMap的程序集扫描没有任何对定义
IRequestService
的程序集的引用,因此在执行此操作时必须使用某种反射。我扫描了“”的答案,但该答案似乎需要对包含接口定义的程序集的引用


我正在尝试编写一个自定义的StructureMap.Graph.ITypeScanner,但我有点纠结于该怎么做(主要是因为我对反射几乎没有经验)。

您使用扫描仪的路径是正确的。谢天谢地,StructureMap中内置了一个。不幸的是,截至撰写本文时,它还没有发布。从trunk获取最新信息,您将看到扫描仪配置中的一些新功能。下面是一个满足您需求的示例

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        Scan(x =>
        {
            x.TheCallingAssembly();
            //x.AssembliesFromApplicationBaseDirectory();
            x.WithDefaultConventions();
            x.ConnectImplementationsToTypesClosing(typeof (IRequestService<>));
        });
    }
}
公共类MyRegistry:Registry
{
公共注册处()
{
扫描(x=>
{
x、 装配件();
//x、 AssembliesFromApplicationBaseDirectory();
x、 使用默认约定();
x、 连接实现到TypesClosing(typeof(IRequestService));
});
}
}
首先,您需要告诉扫描仪配置扫描中要包括哪些程序集。如果您没有对每个程序集执行注册表,则注释的AssembliesFromApplicationBaseDirectory()方法也可能会有所帮助

要将泛型类型放入容器中,请使用ConnectionImplementationsToTypesClosing

有关如何设置容器时使用注册表的示例,请参阅:

如果愿意,您可以跳过使用注册表,只需在ObjectFactory.Initialize中进行扫描即可


希望这有帮助。

谢谢。我会看看这个。目前,我使用的是一个程序集扫描程序,所有解决方案中只有一个注册表(我的解决方案中只有一个项目引用了StructureMap)。我面临的一个问题是,在我的UI项目中有一个通用接口和该接口的多个Impl,但我无法从项目中使用注册表引用UI项目,因为这会导致循环引用,这就是我希望能够使用扫描仪的原因。
public MyController(IFooRequestService fooRequestService) { ... }
public class MyRegistry : Registry
{
    public MyRegistry()
    {
        Scan(x =>
        {
            x.TheCallingAssembly();
            //x.AssembliesFromApplicationBaseDirectory();
            x.WithDefaultConventions();
            x.ConnectImplementationsToTypesClosing(typeof (IRequestService<>));
        });
    }
}