StructureMap有哪些配置文件与Autofac相同?

时间:2017-04-04 06:44:10

标签: c# inversion-of-control autofac structuremap

Autofac与StructureMap的配置文件有什么相似之处

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

1 个答案:

答案 0 :(得分: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

那样使用此代码