【问题标题】:StructureMap: Configure concrete classes at run time?StructureMap:在运行时配置具体类?
【发布时间】:2010-02-15 19:29:59
【问题描述】:

我知道具体类型可以通过以下方式使用结构图进行配置:

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

如果您提前知道类型,则此方法有效。我想在运行时做,似乎没有办法。有人可以启发我吗?我想要做的是类似以下的事情:(结构图似乎不支持)

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

这样做的原因是因为我正在为结构映射的配置开发一个包装器。而且我不会提前知道类型。对于 .Object(new ColorRule("Green")) 我将传入一个委托,它实际上会根据请求构造对象。

【问题讨论】:

    标签: structuremap ioc-container


    【解决方案1】:

    最近 Jeremy 添加了将 Func 配置为您的类型的构建器的功能。这是使用委托/lambda 作为构建器的示例。

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

    【讨论】:

    • 感谢您的尝试,但我不能使用泛型,因为我不会在构建时知道类型,只能在运行时知道。另外,对于我的问题,我需要它来处理无接口对象。但是我确实尝试过这样的方法:cfg.For(typeof(IRule)).Use(builder) 但这会导致结构映射抛出异常:StructureMap configuration failures: Error: 104 ColorfulRule cannot be plugged into type IRule.跨度>
    • 没关系,我认为我能够通过修改您的代码使其工作。感谢您为我指明正确的方向!
    • 很高兴它可以满足您的需求。抱歉,您不能使用它们使使用容器更容易并让您更好地控制抽象的接口。
    • 您是如何解决这个问题的?我刚刚遇到了同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多