Could anyone suggest the xml configuration for the below StuctureMap DI code. BrowserType is enumerator.
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);
});
I'm not really familiar with StructureMap, so I'm going to guess, but I think you can do something like this:
<StructureMap MementoStyle="Attribute">
<DefaultInstance
PluginType="assembly-qualified name of ITranslatorEngine"
PluggedType="assembly-qualified name of Translator"
browserType = "IE" />
</StructureMap>
Assuming that "browserType" is the name of the constructor argument in the Translator class.
You can place the XML in the App.config file or StructureMap.config, and then modify the ObjectFactory.Initialize call to set the appropriate property for the config source.
More details are available on the StructureMap site:
Edit: according to this page, string names of the enumeration should be used as values.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With