首页 > 解决方案 > 一个类的属性作为参数传递给另一个类的构造函数。如何用 Autofac 解决这个问题?

问题描述

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

我有 2 个班级,他们都是单身人士。

其中一个有一些公共财产,例如。

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

第二类有一个构造函数,它应该将第一类的属性作为参数:

public class ClassWithConstructor
  {
    private string _someParameter;

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

没有 Autofac 我可以这样做:

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

我无法使用 Autofac 解决此问题,也无法在此处或谷歌中找到任何解决方案。我所做的:

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 从一个表单传递到另一个视图类,并完全在该 TreeList 上工作。

标签: c#dependency-injectionautofac

解决方案


您可以注册一个 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(); 

推荐阅读