c# - 构造函数枚举参数的 StructureMap 配置

标签 c# dependency-injection structuremap

谁能建议以下 StuctureMap DI 代码的 xml 配置。 BrowserType 是枚举数。

ObjectFactory.Initialize(x =>
{
    // Tell StructureMap to look for configuration 
    // from the App.config file
    // The default is false
    //x.PullConfigurationFromAppConfig = true;
    x.For<ITranslatorEngine>().Use<Translator>().Ctor<BrowserType>().Is(BrowserType.IE);
});

最佳答案

我对 StructureMap 不是很熟悉,所以我会猜测,但我认为你可以这样做:

<StructureMap MementoStyle="Attribute">
  <DefaultInstance
    PluginType="assembly-qualified name of ITranslatorEngine"
    PluggedType="assembly-qualified name of Translator"
    browserType = "IE" />
</StructureMap>

假设“browserType”是 Translator 类中构造函数参数的名称。

您可以将 XML 放在 App.config 文件或 StructureMap.config 中,然后修改 ObjectFactory.Initialize 调用以为配置源设置适当的属性。

更多详细信息可在 StructureMap 网站上找到:

编辑:根据this page , 枚举的字符串名称应该用作值。


这是一个基于 StructureMap 2.6.1 的完整示例:

Translator.cs:

namespace StructureMapTests
{
    public interface ITranslator
    {
    }

    public enum BrowserType
    {
        IE,
        Firefox,
        Chrome
    }

    public class Translator : ITranslator
    {
        public Translator(BrowserType browserType)
        {

        }
    }
}

程序.cs:

namespace StructureMapTests
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ObjectFactory.Initialize(x => 
                           { 
                              x.PullConfigurationFromAppConfig = true; 
                           });

                var translator = ObjectFactory.GetInstance<ITranslator>();

                Console.WriteLine(translator == null);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadLine();
        }
    }
}

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="StructureMap" type="StructureMap.Configuration.StructureMapConfigurationSection,StructureMap"/>
  </configSections>

  <StructureMap MementoStyle="Attribute">
    <DefaultInstance PluginType="StructureMapTests.ITranslator, StructureMapTests" 
                     PluggedType="StructureMapTests.Translator, StructureMapTests"
                     browserType="IE">

    </DefaultInstance>
  </StructureMap>
</configuration>

关于c# - 构造函数枚举参数的 StructureMap 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5594670/

相关文章:

c# - 实现智能搜索/模糊字符串比较

c# - 在给定复杂继承的情况下保持一致的松散耦合

c# - 使用 Autofac 4 和 vNext 自注册库

wcf - wcf 中的 Entity Framework DbContext 每次调用实例模式

c# - 如何使用 GroupBy() 对多个项目进行分组?

c# - 当我将可空 int 转换为字符串时,为什么 null 合并运算符不对它起作用?

dependency-injection - 温莎城堡传递构造函数参数

c# - 如何使用 StructureMap 将服务注入(inject) XAML 引用的 ViewModel?

c# - 使用 Structure Map 替换泛型类型参数中的抽象类型

c# - 我们可以根据在 C# 中调用函数的位置来更改函数行为吗?