【问题标题】:How to use custom factory with Structuremap?如何在 Structuremap 中使用自定义工厂?
【发布时间】:2023-03-19 01:16:01
【问题描述】:

我有一个场景,我的班级依赖于两个服务。但是,我正在使用提供程序模式并有一个自定义工厂,它返回从 app.config 文件读取的这些服务的实例。

这是我要实现的示例场景代码

public class ClassA
{
     public ClassA(IServiceA serviceA, IServiceB)
     {
         // ServiceA and ServiceB are instantiated through a factory class
     }

     public ClassA(IServiceFactory factory)
     {
         // I want to use this constructor and use this factory and call the above constructor
     }
}

在上面的代码中,我的 ClassA 需要 ServiceA 和 ServiceB,但我想使用我的工厂来创建这些类的实例,因此我创建了另一个依赖于工厂类的构造函数。现在从结构映射中,我想创建一个使用每个类的构造函数并正确解析工厂的配置。我不想手动为每个类定义映射,而是创建一个可以正确解析每个类的配置规则。

我不知道该怎么做?请给点建议。

【问题讨论】:

  • 你还在为这个问题而烦恼吗?
  • @JoeMighty 是的,如果你能帮助我,那就太好了!

标签: c# dependency-injection structuremap structuremap3


【解决方案1】:

您可能希望查看使用工厂方法注册让 StructureMap 解析 IA 和 IB 并返回一个新的 ClassA 实例,直接调用构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多