StructureMap: Configure concrete classes at run time?
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 kn开发者_运维知识库ow 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.
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");
}
}
精彩评论