how to Tell StructureMap to use a specific constructor?

738 Views Asked by At

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");
    });
}
1

There are 1 best solutions below

0
On

Since XPathDocument is a framework type that is not under your control, you should register it with a factory delegate.

container.Configure(r => r.For<XPathDocument>()
    .Use(() => new XPathDocument("XmlFile1"));

But since you need a dofference instance per service, you might be better of not registering this class itself, but only configure your services with a constructor argument where you specify the lambda delegate.