如何在Autofac中定义运行时嵌套对象的值

时间:2014-09-08 23:14:50

标签: c# inversion-of-control autofac

假设我有以下层次结构。

class PersonWithJacket
{
    public PersonWithJacket(Jacket jacket)
    {
    }
}

class Jacket
{
    public Jacket(string brand)
    {
    }
}

我在Autofac容器中注册这些类

        containerBuilder.RegisterType<PersonWithJacket>();
        containerBuilder.RegisterType<Jacket>();

在运行时,我想解析一个PersonWithJacket对象,我想定义嵌套string brand类的Jacket构造函数参数。我的第一种方法是使用NamedParameter,如此:

        var personWithJacket = container.Resolve<PersonWithJacket>(new NamedParameter("brand", "TheBrand"));

我将其视为“解析a PersonWithJacket对象,如果遇到名为'brand'的构造函数参数,请使用值'TheBrand'”但字符串参数无法解析。

有没有办法在运行时定义嵌套对象的构造函数参数的值?

2 个答案:

答案 0 :(得分:1)

哦,没关系。 ResolvedParameter s并没有那么糟糕。

        using (var scope = container.BeginLifetimeScope()) {
            var someDynamicString = "Brand B";

            var personDude = scope.Resolve<PersonWithJacket>(new ResolvedParameter(
                (pi, ctx) => pi.ParameterType == typeof(Jacket),
                (pi, ctx) => ctx.Resolve<Jacket>(new NamedParameter("name", someDynamicString))));
        }

答案 1 :(得分:1)

这样做的方法似乎是使用容器层次结构。我创建了一个基本容器,我在其中注册所有常见类型和实例,然后创建子容器来注册变化的部分。

var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<PersonWithJacket>();

var childContainer1 = new MultitenantContainer(new NullTenantIdStrategy(), containerBuilder.Build());
childContainer1.ConfigureTenant(null, builder => builder.Register(context => new Jacket("Hugo Boss")));

var childContainer2 = new MultitenantContainer(new NullTenantIdStrategy(), containerBuilder.Build());
childContainer2.ConfigureTenant(null, builder => builder.Register(context => new Jacket("H&M")));

var personWithHugoBossJacket = childContainer1.Resolve<PersonWithJacket>();
var personWithHandMJacket = childContainer2.Resolve<PersonWithJacket>();