东西从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
验证码
你能简单解释一下配置文件的用途吗? –
配置文件允许基于运行时条件(配置文件名称)更改对象图的结构。 – Steven