2

高水平

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

例子:

  • FooRequestServiceIRequestService<FooRequest>在请求时注入
  • BarRequestServiceIRequestService<BarRequest>在请求时注入

细节

我定义了一个通用接口

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

然后我有多个实现这个接口的请求对象

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注入)

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

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

public interface IFooRequestService : IRequestService<Foo> { }

然后我的控制器 ctor 看起来像这样,它与 StructureMaps 的 Default Convention Scanner 一起使用

public MyController(IFooRequestService fooRequestService) { ... }

我如何使用 StructureMap 的程序集扫描器创建一个规则来注册所有名为 TRequestService 的对象IRequestService<T>(其中 T = "Foo"、"Bar" 等),这样我就不必创建这些空的接口定义?

为了将其他东西加入其中,我正在处理 StructureMap 的程序集扫描没有对定义的程序集的任何引用,IRequestService<T>因此在执行此操作时必须使用某种反射。我扫描了“使用 Scan 为泛型类型自动注册 StructureMap 自动注册”的答案,但似乎该答案需要引用包含接口定义的程序集。

我正在尝试编写自定义 StructureMap.Graph.ITypeScanner,但我有点坚持在那里做什么(主要是因为我对反射的经验很少)。

4

1 回答 1

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中进行扫描。

希望这可以帮助。

于 2009-09-03T15:19:49.713 回答