1

I know that Concrete Types can be configured with Structure Map the following way:

ForRequestedType<Rule>().TheDefault.Is.Object(new ColorRule("Green"));

This works if you know the type ahead of time. I want to do it at run time, and there does not seem to be a way. Can some one enlighten me? What I want to do is something like the following: (This appears to be not supported by structure map)

ForRequestedType(typeof(Rule)).TheDefault.Is.Object(new ColorRule("Green"));

The reason for this is because I'm working on a wrapper for structure-map's configuration. And I will not know the type ahead of time. For the .Object(new ColorRule("Green")) I am going to be passing in a delegate instead, which would actually construct the object on request.

7wp
  • 12,505
  • 20
  • 77
  • 103

1 Answers1

2

Recently Jeremy added the ability to configure a Func as a builder for your type. Here is an example of using a delegate/lambda as your builder.

    public interface IRule
{
    string Color { get; set; }
}

public class ColorfulRule : IRule
{
    public string Color { get; set; }

    public ColorfulRule(string color)
    {
        Color = color;
    }
}

[TestFixture]
public class configuring_delegates
{
    [Test]
    public void test()
    {
        var color = "green";
        Func<IRule> builder = () => new ColorfulRule(color);

        var container = new Container(cfg=>
        {
            cfg.For<IRule>().Use(builder);
        });

        container.GetInstance<IRule>().Color.ShouldEqual("green");

        color = "blue";

        container.GetInstance<IRule>().Color.ShouldEqual("blue");
    }
}
KevM
  • 2,496
  • 1
  • 22
  • 25
  • Thanks for trying but I can't use the Generics, since I am not going to know the type at build time, only at run time. Also, for my problem I need it to work with interface-less objects. however I did try your method like this: cfg.For(typeof(IRule)).Use(builder) but that causes structure map to throw an exception: StructureMap configuration failures: Error: 104 ColorfulRule cannot be plugged into type IRule. – 7wp Feb 16 '10 at 05:59
  • Never mind I think I was able to make it work with modification of your code. Thanks for pointing me in the right direction! – 7wp Feb 16 '10 at 06:11
  • Glad you got it working for your needs. Sorry you can't use interfaces they make working with containers much easier and give you better control over your abstractions. – KevM Feb 16 '10 at 13:35
  • 1
    How did you manage to solve this? I've just run in the same problem. – Gaz Aug 12 '11 at 16:03