views:

338

answers:

2

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.

+1  A: 

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
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.
Roberto Sebestyen
Never mind I think I was able to make it work with modification of your code. Thanks for pointing me in the right direction!
Roberto Sebestyen
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
A: 

Roberto Sebestyen- What were the modifications that you made to make it work? I'm running into the same issue. Thanks!

RicHokie
http://blog.noobtech.com/index.php/2010/02/decoupling-application-code-from-ioc-implementation/ Take a look in StructureMapIocHelper implementation class, right under the comment //Register Concrete types with Structure Map
Roberto Sebestyen