使用StructureMap配置配置文件

时间:2009-02-19 18:16:02

标签: .net configuration structuremap

重要;我真的在这里寻找StructureMap答案。请不要说如何使用Windsor,Spring,Unity或任何the others

我正在使用StructureMap来玩IoC - 基本上我的目标是拥有一个定义核心类型的“默认”配置文件,以及一些覆盖/扩展它的命名配置文件。我认为这些配置文件可以做到这一点,但我无法通过xml或代码API使其工作。特别是,如果我尝试为配置文件加载容器:

container = new Container();
container.SetDefaultsToProfile(profile);

然后我得到“请求的个人资料{name}无法找到”,尽管我在初始化中明确地调用CreateProfile(使用该名称)。

我是在咆哮错误的树吗?

(也张贴到user-group


我理想的是能够定义标准(/ default) 类型,然后是一系列不同的命名配置, 覆盖一些设置 - 即如果我有

  • global:IFoo => FooIBar => Bar
  • configA :(无变化)
  • configB:IFoo => SpecialFoo

我相信这可以映射到2个容器,使用命名的配置文件加载。 目的是如果我问任何一个容器IBar,我得到一个 Bar - 但是configA返回Foo(对于IFoo),其中 - 作为configB返回 SpecialFoo

有人能告诉我如何配置这个吗? xml或者 代码很好......我只想让它工作。我只需要接口到 - 具体类型映射(没有特殊的配置/属性设置)。

2 个答案:

答案 0 :(得分:9)

诀窍是确保每个配置文件至少是其中定义的规则。如果您未指定规则(configA),则不会创建/查看配置文件。

鉴于这些课程:

public interface IFoo { string SayHello(); }
public class Foo : IFoo { public string SayHello() { return "Hello"; } }
public class SpecialFoo : IFoo { public string SayHello() { return "Hello Special"; } }

public interface IBar { }
public class Bar : IBar { }

public interface IDummy { }
public class Dummy : IDummy{ }

您可以定义此注册表:

public class MyRegistry : Registry
{
    protected override void configure()
    {
        ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar>();
        ForRequestedType<IFoo>().TheDefault.Is.OfConcreteType<Foo>();
        CreateProfileNotEmpty("configA");
        CreateProfileNotEmpty("configB")
            .For<IFoo>().UseConcreteType<SpecialFoo>();
    }
    StructureMap.Configuration.DSL.Expressions.ProfileExpression CreateProfileNotEmpty(string profile)
    {
        return CreateProfile(profile)
            .For<IDummy>().UseConcreteType<Dummy>();
    }
}

它将适用于这些测试:

[TestMethod]
public void TestMethod1()
{
    var container = new Container(new MyRegistry());
    Assert.IsNotNull(container.GetInstance<IBar>());
    Assert.AreEqual("Hello", container.GetInstance<IFoo>().SayHello());

    container.SetDefaultsToProfile("configB");
    Assert.IsNotNull(container.GetInstance<IBar>());
    Assert.AreEqual("Hello Special", container.GetInstance<IFoo>().SayHello());

    container.SetDefaultsToProfile("configA");
    Assert.IsNotNull(container.GetInstance<IBar>());
    Assert.AreEqual("Hello", container.GetInstance<IFoo>().SayHello());
}

如果用简单的CreateProfile替换CreateProfileNotEmpty,它将在将默认值设置为configA的行上失败。

答案 1 :(得分:1)

观看此视频,他展示了另一种方法,即执行“默认”配置文件,并使用其他命名配置文件作为变体。

http://www.dimecasts.net/Casts/CastDetails/135