2014-10-08 83 views
1

是否存在一個爲以「x」命名的構造函數參數指定值的約定。例如,請執行以下操作結構圖構造函數參數注入約定

對於任何請求的依賴項,具有名爲「pathToFile」的構造函數參數提供此值。

我可以用For語法和ctor來做到這一點,但不能爲我想要配置的每個類編寫相同的一段代碼。

public class FileManager(string pathToFile):IDocumentManager 
{ 

} 

當過我請求IDocumentManager(依賴)它(實例)有一個名爲pathToFile參數的構造函數,所以我希望它得到一些價值

回答

1

它可以創建自定義的約定注入。通過執行IRegistrationConvention創建約定。然後在Process方法中檢查類型是否爲具體類型,檢查它是否具有所需的構造函數參數,然後爲其實現的所有接口註冊構造函數的參數,並鍵入其自身。我正在使用這種約定來注入連接字符串。

public class ConnectionStringConvention : IRegistrationConvention 
{ 
    public void Process(Type type, Registry registry) 
    { 
     if (!type.IsConcrete() || type.IsGenericType) return; 

     if (!HasConnectionString(type)) return; 

     type.GetInterfaces().Each(@interface => 
     { 
      registry.For(@interface) 
       .Use(type) 
       .WithProperty("connectionString") 
       .EqualTo(SiteConfiguration.AppConnectionString); 
     }); 

     registry.For(type) 
      .Use(type) 
      .WithProperty("connectionString") 
      .EqualTo(SiteConfiguration.AppConnectionString); 
    } 

    private bool HasConnectionString(Type type) 
    { 
     return type.GetConstructors() 
      .Any(c => c.GetParameters() 
       .Any(p => p.Name == "connectionString")); 
    } 
} 

約定創建後,在您的容器配置寄存器是:

Scan(x => 
{ 
    x.TheCallingAssembly(); 
    x.WithDefaultConventions(); 
    x.Convention<ConnectionStringConvention>(); 
}); 

欲瞭解更多信息檢查:

http://structuremap.github.io/registration/auto-registration-and-conventions/

http://www.sep.com/sep-blog/2010/06/04/teaching-structuremap-about-c-4-0-optional-parameters-and-default-values/