Tell StructureMap to use a specific constructor
Asked Answered
S

1

38

I have two services that require an XPathDocument. I want to be able to define named instances of XPathDocumnet to use in the configuration of the two services. I also want to be able to tell StuctureMap which constructor of XPathDocument to use. When I try to get an instance of XPathDocument it tells me that it can't find the plugged type for XmlReader. I want to use the constructor that requires a string uri for the xml file. I cannot seem to get this to work. Here is the StructureMap configuration code.

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");
    });
}
Superposition answered 11/12, 2008 at 15:30 Comment(2)
S
2

Look at this. In short, you need to change OfConcreteType<Service1>() to ConstructedBy(() => new Service1());.

Spindly answered 27/12, 2013 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.