2017-04-04 95 views
0

确实Autofac有类似StructureMap的档案StructureMap具有什么与Autofac相同的配置文件?

IContainer container = new Container(registry => 
{ 
    registry.Profile("something", p => 
    { 
     p.For<IWidget>().Use<AWidget>(); 
     p.For<Rule>().Use<DefaultRule>(); 
    }); 
}); 
+1

你能简单解释一下配置文件的用途吗? –

+0

配置文件允许基于运行时条件(配置文件名称)更改对象图的结构。 – Steven

回答

0

东西从StructureMap documentation

型材刚刚命名的可以通过注册表配置配置前期子容器。

创建一个孩子一生的范围时,您可以在Autofac相同的行为。

using (ILifetimeScope scope = container.BeginLifetimeScope(childBuilder => 
{ 
    childBuilder.RegisterType<AWidget>().As<IWidget>(); 
    childBuilder.RegisterType<DefaultRule>().As<Rule>(); 
})) 
{ 
    // do things 
} 

如果你想命名它,你可以使用一个标签,它是一个对象,而不仅仅是一个字符串。

using (ILifetimeScope scope = container.BeginLifetimeScope("something", childBuilder => 
{ 
    childBuilder.RegisterType<AWidget>().As<IWidget>(); 
    childBuilder.RegisterType<DefaultRule>().As<Rule>(); 
})) 
{ 
    // do things 
} 

如果你想拥有GetProfile方法的等价性,您可以使用此代码示例:

ContainerBuilder builder = new ContainerBuilder(); 

builder.Register(c => c.Resolve<ILifetimeScope>() 
      .BeginLifetimeScope("A", _ => 
      { 
       _.RegisterType<FooA>().As<IFoo>(); 
      })) 
     .Named<ILifetimeScope>("A"); 

builder.Register(c => c.Resolve<ILifetimeScope>() 
      .BeginLifetimeScope("B", _ => 
      { 
       _.RegisterType<FooB>().As<IFoo>(); 
      })) 
     .Named<ILifetimeScope>("B"); 

// build the root of all profile 
IContainer container = builder.Build(); 

// get the profile lifetimescope 
ILifetimeScope profileScope = container.ResolveNamed<ILifetimeScope>("B"); 

// use a working lifetimescope from your profile 
using (ILifetimeScope workingScope = profileScope.BeginLifetimeScope()) 
{ 
    IFoo foo = workingScope.Resolve<IFoo>(); 
    Console.WriteLine(foo.GetType()); 
} 

顺便说一句,要小心没有使用像service locator anti pattern

验证码
+0

嗨,Cyril,我相信在StructureMap中的Child和Nested容器之间存在区别,如文档中所述 - > Child Containers不能与嵌套容器互换。有关嵌套容器的更多信息,请参阅嵌套容器(每请求/事务)。 – CRG

+0

但是,重新注册新的LifetimeScope应该可行。感谢您的反馈意见! – CRG

相关问题