结构图通用类型扫描仪

时间:2009-08-21 18:58:45

标签: structuremap

高级

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

示例:

    在请求FooRequestService时注入
  • IRequestService<FooRequest>
  • 在请求BarRequestService时注入
  • IRequestService<BarRequest>

详情

我定义了通用接口

public interface IRequestService<T> where T : Request
{
    Response TransformRequest(T request, User current);
}

然后我有多个实现此接口的Request对象

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

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

现在我需要注册这些类,以便StructureMap知道如何创建它们,因为在我的控制器中我想要有以下ctor(我希望StructureMap注入FooRequestService)< / p>

public MyController(IRequestService<Foo> fooRequestService) { ... }

现在为了解决我的问题,我实现了一个空接口,而不是让FooRequestService实现通用接口,我让它实现了这个空接口

public interface IFooRequestService : IRequestService<Foo> { }

然后我的控制器ctor看起来像这样,它与StructureMaps的默认会议扫描仪

一起使用
public MyController(IFooRequestService fooRequestService) { ... }

我怎么能用StructureMap的汇编扫描器创建一个规则来注册名为TRequestService的所有对象IRequestService<T>(其中T =“Foo”,“Bar”等),这样我就不必创建这些空接口定义?

要将其他内容添加到混合中,我在处理StructureMap的程序集扫描没有任何对定义IRequestService<T>的程序集的引用,因此在执行此操作时必须使用某种反射。我将答案扫描到“StructureMap Auto registration for generic types using Scan”,但似乎答案需要引用包含接口定义的程序集。

我正在尝试编写一个自定义的StructureMap.Graph.ITypeScanner,但我仍然不知道该做什么(主要是因为我对反射的经验很少)。

1 个答案:

答案 0 :(得分:2)

您在使用扫描仪的正确道路上。值得庆幸的是,StructureMap内置了一个。不幸的是,截至本文撰写时,尚未发布。从主干获取最新信息,您将在扫描仪配置中看到一些新功能。以下是您需求的一个示例。

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        Scan(x =>
        {
            x.TheCallingAssembly();
            //x.AssembliesFromApplicationBaseDirectory();
            x.WithDefaultConventions();
            x.ConnectImplementationsToTypesClosing(typeof (IRequestService<>));
        });
    }
}

首先,您需要告诉扫描仪配置扫描中包含哪些程序集。如果您没有为每个程序集执行注册表,则注释 AssembliesFromApplicationBaseDirectory()方法也可能会有所帮助。

要将通用类型放入容器,请使用 ConnectImplementationsToTypesClosing

有关如何在设置容器时设置使用注册表的示例,请参阅: http://structuremap.sourceforge.net/ConfiguringStructureMap.htm

如果您愿意,可以跳过一般的注册表,只需在 ObjectFactory.Initialize 中进行扫描。

希望这有帮助。