构造函数枚举参数的StructureMap配置

3

有人能为下面的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);
});
1个回答

1

我对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网站:

编辑:根据此页面,应使用枚举的字符串名称作为值。


以下是基于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)
        {

        }
    }
}

Program.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>

是的,'browserType' 是一个 Translator 构造函数参数。因为它是一个枚举类型,我们不能将其归属为 browserType="BrowserType.IE"。当我这样做时,它会给我一个异常 "StructureMap Exception Code: 205,缺少请求的实例属性 'browserType',实例键为"。 - Praveen
@Praveen 你遇到了什么错误?我建立了一个假的控制台应用程序项目作为测试。相关代码在我的答案中。 - Adam Lear

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接