谁能为下面的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
调用以为config源设置适当的属性。可在StructureMap网站上找到更多详细信息:
Configuring StructureMap
Xml Configuration
编辑:根据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();
}
}
}
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# - 构造函数Enum参数的StructureMap配置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5594670/