簡體   English   中英

使用Autofac將組件屬性注入到另一個組件的構造函數參數中

[英]Inject a component property into another component's constructor parameter with Autofac

使用Autofac IoC容器,可以說有以下情形:

public interface IHaveASpecialProperty
{
  SpecialType SpecialProperty { get; }
}

public class HaveASpecialPropertyImpl : IHaveASpecialProperty
{
  // implementation
}

public class SomeComponent
{
  public SomeComponent(SpecialType special)
  {
    _special = special;

    // rest of construction
  }

  private readonly SpecialType _special;

  // implementation: do something with _special
}

// in composition root:

containerBuilder.RegisterType<HaveASpecialPropertyImpl>
  .As<IHaveASpecialProperty>();

containerBuilder.RegisterType<>(SomeComponent);

有沒有一種方法可以在Autofac容器中注冊HaveASpecialPropertyImpl類型以充當SpecialType實例的提供者/工廠?

我目前擁有的是這種經典方法:

public class SomeComponent
{
  public SomeComponent(IHaveASpecialProperty specialProvider)
  {
    _special = specialProvider.SpecialProperty;

    // rest of construction
  }

  private readonly SpecialType _special;

  // implementation: do something with _special
}

基本原理基本上與Demeter定律有關: specialProvider僅用於獲取SpecialType實例,而后者是SomeComponent所需和使用的實際依賴關系,因此,僅在不考慮SomeComponent情況下注入SpecialType實例似乎是合理的。實例來自。

PS:我讀過有關代表工廠的文章 ,不確定這是否是(唯一的)方法。

您可以注冊一個代表:

builder.Register(c => c.Resolve<IHaveASpecialProperty>().SpecialProperty)
       .As<ISpecialType>(); 

使用此注冊,每次您解析ISpecialType Autofac都會解析IHaveASpecialProperty並將SpecialProperty屬性值返回為ISpecialType

暫無
暫無

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

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