告诉StructureMap使用特定的构造函数。

38

我有两个需要使用XPathDocument的服务。我希望能够定义XPathDocument的命名实例,并在配置这两个服务时使用。我还想告诉StuctureMap使用哪个XPathDocument构造函数。当我尝试获取XPathDocument实例时,它告诉我找不到XmlReader的插入类型。我想使用需要xml文件字符串uri的构造函数,但无法似乎让它工作。以下是StructureMap配置代码。

public class Service1 : IService1 {
    public Service1(XPathDocument document) {}
}
public class Service2 : IService2 {
    public Service2(XPathDocument document) {}
}

public class Registry1 : Registry {
    ForRequestedType<IService1>().TheDefault.Is.OfConcreteType<Service1>()
        .CtorDependency<XPathDocument>()
        .Is(x => x.TheInstanceNamed("XPathDocument1"));
    ForRequestedType<IService2>().TheDefault.Is.OfConcreteType<Service2>()
        .CtorDependency<XPathDocument>()
        .Is(x => x.TheInstanceNamed("XPathDocument2"));

    ForRequestedType<XPathDocument>().AddInstances(x => {
        x.OfConcreteType<XPathDocument>()
            .WithCtorArg("uri").EqualToAppSetting("XmlFile1")
            .WithName("XPathDocument1");
        x.OfConcreteType<XPathDocument>()
            .WithCtorArg("uri").EqualToAppSetting("XmlFile2")
            .WithName("XPathDocument2");
    });
}

3
请参见 https://dev59.com/aHVC5IYBdhLWcg3wcwwm。该链接讨论了如何通过代码定义 StructureMap 的默认构造函数。 - Markus Dulghier
可能是重复的问题:StructureMap:如何通过代码定义默认构造函数? - Richard Ev
1个回答

2

看这个链接。简单来说,你需要将OfConcreteType<Service1>()改为ConstructedBy(() => new Service1());


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接