.NET手記-Autofac進階(傳遞注冊參數 Passing Parameters to Register)


當你注冊組件時,可以為組件服務傳入一系列參數,用於服務解析時使用。

 

可使用的參數類型 Available Parameter Types

 

Autofac提供了集中參數匹配類別:

  • NamedParameter - 直接通過名稱匹配目標參數
  • TypedParameter - 通過類型來匹配目標參數
  • ResolvedParameter - 靈活的參數匹配

NamedParameter 和 TypedParameter只支持常量。

ResolvedParameter 能夠使用從容器中動態解析的值作為參數, 例如通過名字解析出的服務。

 

反射組件的參數 Parameters with Reflection Components

 

當你注冊基於反射的組件時,類型構造函數可能要求一些無法從容器中解析的參數。你可以通過直接提供此參數來完成組件注冊。

假設你有一個配置閱讀器(configuration reader),同時需要為它傳入配置塊命名(configuration section name):

 

public class ConfigReader : IConfigReader
{
  public ConfigReader(string configSectionName)
  {
    // Store config section name
  }

  // ...read configuration based on the section name.
}

 

你可能會使用Lambda表達式來實現:

 

builder.Register(c => new ConfigReader("sectionName")).As<IConfigReader>();

 

或者為反射組件注冊時傳入參數:

 

// Using a NAMED parameter:
builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter("configSectionName", "sectionName");

// Using a TYPED parameter:
builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter(new TypedParameter(typeof(string), "sectionName"));

// Using a RESOLVED parameter:
builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter(
         new ResolvedParameter(
           (pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "configSectionName",
           (pi, ctx) => "sectionName"));

 

Lambda表達式組件的參數 Parameters with Lambda Expression Components

 

使用Lambda表達式,而不是在組件注冊時直接傳入參數能夠保證動態參數在服務被調用時被傳入。

在組件注冊表達式中,你可以通過改變用語注冊組件的委托簽名來使用傳入的參數。可以使用具有一個IComponentContext參數和一個IEnumerable<Parameter>參數的委托來替代只使用單個IComponentContext參數的委托。

 

// Use TWO parameters to the registration delegate:
// c = The current IComponentContext to dynamically resolve dependencies
// p = An IEnumerable<Parameter> with the incoming parameter set
builder.Register((c, p) =>
                 new ConfigReader(p.Named<string>("configSectionName")))
       .As<IConfigReader>();

 

當通過使用參數解析組件時,你的Lambda表達式將會使用傳入的參數:

 

reader = scope.Resolve<IConfigReader>(new NamedParameter("configSectionName", "sectionName"));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM