簡體   English   中英

一個 class 的屬性作為參數傳遞給另一個 class 的構造函數。 如何用 Autofac 解決這個問題?

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

我是 Autofac 的新手,這是我的問題的場景:

我有 2 個班級,他們都是單身人士。

其中一個有一些公共財產,例如。

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 解決此問題,也無法在此處或谷歌中找到任何解決方案。 我所做的:

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(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM