Autofac lazy TypedParameter

时间:2011-03-16 04:00:43

标签: autofac

Autofac中是否可以使TypedParameter懒惰?更重要的是,我需要在注入参数时访问容器。代码可能如下所示:

builder.RegisterType<RootService>()
    .WithParameter(TypedParameter.From(c => c.Resolve<IChildService>(key)));

更新

根据Nick的回答,我创建了以下帮助方法:

public static class TypedResolvedParameter 
{
    public static ResolvedParameter From<T>(Func<IComponentContext, T> factory)
    {
        return new ResolvedParameter(
            (pi, c) => pi.ParameterType == typeof(T),
            (pi, c) => factory(c));
    }
}

1 个答案:

答案 0 :(得分:9)

您正在寻找ResolvedParameter,也可以作为WithParameter()的重载:

builder.RegisterType<RootService>()
  .WithParameter((pi, c) => pi.ParameterType == typeof(IChildService),
                 (pi, c) => c.ResolveNamed<IChildService>(key));