2011-04-08 118 views
3

任何人都可以爲下面的StuctureMap DI代碼建議xml配置。 BrowserType是枚舉數。構造函數的StructureMap配置枚舉參數

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); 
}); 
+0

你使用spring-mvc嗎? – kalyan 2011-04-08 12:05:03

+0

不,asp.net mvc 2 – Praveen 2011-04-11 04:27:41

回答

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:

編輯:根據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) 
     { 

     } 
    } 
} 

的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(); 
     } 
    } 
} 

應用.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> 
+0

是的,'browserType'是一個Translator構造函數參數。因爲它是一個枚舉,我們不能將它歸類爲browserType =「BrowserType.IE」。當我這樣做,它給了我一個例外「StructureMap例外代碼:205 缺少請求實例屬性」browserType「爲InstanceKey」 – Praveen 2011-04-11 04:31:16

+0

@Praveen我更新了我的答案。希望能幫助到你。 – 2011-04-11 20:20:39

+0

仍然沒有運氣:(.. – Praveen 2011-04-13 04:18:46

相關問題