我收到了这个错误:
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily
我的设置如下:
Console.WriteLine("Structure Map");
SetupSM sm = new SetupSM();
sm.Setup();
ISomeThing someThing = ObjectFactory.GetInstance<ISomeThing>();
Console.WriteLine("something.HowManyTHings: " + someThing.HowManyThings("asdf"));
public class SetupSM
{
public void Setup()
{
var c1 = new Container(config =>
{
config.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
});
var c2 = new Container(x =>
{
x.For<ISomeThing>().Use<SomeThingOne>();
});
}
}
这是我第一次尝试使用结构图,我错过了什么? 看来他们主网站上的指南使用旧语法等很老了。
答案 0 :(得分:5)
尝试将您的配置应用于静态ObjectFactory,而不是立即丢弃的单独容器。
public class SetupSM
{
public void Setup()
{
ObjectFactory.Configure(config =>
{
config.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
config.For<ISomething>().Use<SomeThingOne>();
});
}
答案 1 :(得分:3)
以前的答案适用于StructureMap 2或3,但在StructureMap 4中语法已更改。您可以在此处查看完整的解决方案:
http://ardalis.com/using-structuremap-4-in-a-console-app
实际上,ObjectFactory已被Container实例取代。您还可以选择在单独的Registry实例中执行配置,建议使用此实例。因此,Main()中的初始化代码变为:
static void Main(string[] args)
{
var container = Container.For<ConsoleRegistry>();
var app = container.GetInstance<Application>();
app.Run();
Console.ReadLine();
}
这使Main非常干净,并允许Application通过dependency injection请求所需的任何依赖项,并遵循Explicit Dependencies Principle。这些组合使您的应用程序非常易于组合和可测试。
答案 2 :(得分:1)
public static class StructureMapBootStrapper
{
public static void BootStrap()
{
StructureMap.ObjectFactory.Initialize(
bootStrapper =>
{
bootStrapper.For<ISomeThing>().Use<SomeThingOne>();
});
}
}
您的控制台应用:
Console.WriteLine("Structure Map");
StructureMapBootStrapper.BootStrap();
ISomeThing someThing = ObjectFactory.GetInstance<ISomeThing>();
Console.WriteLine("something.HowManyTHings: " + someThing.HowManyThings("asdf"));