.net - 使用 StructureMap 配置配置文件

标签 .net configuration structuremap

重要;我真的在寻找 StructureMap在这里回答。请不要说出如何使用 Windsor、Spring、Unity 或任何 the others 来做到这一点.

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

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

然后我得到“无法找到请求的配置文件 {name}”,尽管我在初始化中明确调用了 CreateProfile(使用该名称)。

我是不是找错树了?

(也发布到 user-group )

<小时/>

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

  • 全局:IFoo => FooIBar => Bar
  • configA:(无更改)
  • configB:IFoo => SpecialFoo

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

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

最佳答案

诀窍是确保每个配置文件至少都作为其中定义的规则。如果您不指定规则 (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());
}

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

关于.net - 使用 StructureMap 配置配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/566506/

相关文章:

c# - 结构图 - 在运行时用模拟对象替换接口(interface)

c# - 如何将 System.Type 列表传递到方法中?

.net - 我如何了解基于 .net 的应用程序正在使用哪个版本的 dotnet?

c# - 是否可以在 Azure 函数中保留环境设置?

java - 与 Action 和拦截器不同的字符串

visual-studio-2010 - Visual Studio:在项目或解决方案设置上设置默认项目

c# - StructureMap 针对所有可能的具体实现注册通用类型

c# - 如何打破存储库之间的循环依赖

c# - 在 C# 中不使用内置函数或方法求和平均最小最大值