一个 class 的 属性 作为参数传递给另一个 class 的构造函数。如何用 Autofac 解决这个问题?

Property of one class is passed as parameter to constructor of another class. How to resolve this with Autofac?

我是 Autofac 的新手,这是我的问题场景:

我有2个class,都是单身

其中一个有一些 public 属性,例如

public class ClassWithProperty
{
  public string SomeProperty { get; set; }
}

和第二个 class 有一个构造函数,它应该从第一个 class 中获取一个 属性 作为参数:

public class ClassWithConstructor
  {
    private string _someParameter;

    public ClassWithConstructor(string someParameter)
    {
      _someParameter = someParameter;
    }
  }

如果没有 Autofac,我可以这样做:

var classWithProperty = new ClassWithProperty();
var classWithConstructor = new ClassWithConstructor(classWithProperty.SomeProperty);

我无法使用 Autofac 解决此问题,并在此处或 google 中找到任何解决方案。 我做什么:

var builder = new ContainerBuilder();

builder.RegisterType<ClassWithProperty>().InstancePerLifetimeScope();
builder.RegisterType<ClassWithConstructor>()
    .WithParameter() // what should be done here to pass exactly ClassWithProperty.SomeProperty here?
    .InstancePerLifetimeScope();
var container = builder.Build();

当然这是简化的场景,只是为了说明我的问题。在真实场景中,我将 TreeList 从一种形式传递到另一种视图 class 并准确地处理该 TreeList。

您可以注册一个 lambda 来手动构建您的 ClassWithConstructor

var builder = new ContainerBuilder();

builder.RegisterType<ClassWithProperty>()
       .InstancePerLifetimeScope();
builder.Register(c => new ClassWithConstructor(c.Resolve<ClassWithProperty>().SomeProperty))
       .InstancePerLifetimeScope(); 

var builder = new ContainerBuilder();

builder.RegisterType<ClassWithProperty>()
       .InstancePerLifetimeScope();
builder.Register<ClassWithConstructor>()
       .WithParameter(new ResolvedParameter(
              (pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "someParameter",
              (pi, ctx) => "sectionName"))
       .InstancePerLifetimeScope();