2017-04-26 112 views
1

我想使用Autofac配置創建一個服務對象。Autofac配置與KeyFilter構造屬性

public class Service : IService 
{ 
     public Service([KeyFilter("eod")]ISimpleMongoClient eodClient, 
      [KeyFilter("live")]ISimpleMongoClient liveClient 
      ) : base(config) 
     { 
      _eodClient = eodClient; 
      _liveClient = liveClient; 
     } 
} 

public class SimpleMongoClient : ISimpleMongoClient 
{ 
    public SimpleMongoClient(string connectionString, string database) 
    { 
     IMongoClient client = new MongoClient(connectionString); 
     MongoDatabase = client.GetDatabase(database); 
    } 
} 

不知何故,使用以下配置,它無法正確解析ISimpleMongoClient參數。我還有什麼遺漏?

{ 
    "components": [ 
    { 
     "type": "Service, TestProject", 
     "services": [ 
     { 
      "type": "IService, TestProject" 
     } 
     ], 
     "instanceScope": "single-instance" 
    }, 
    { 
     "type": "SimpleMongoClient, TestProject", 
     "services": [ 
     { 
      "type": "ISimpleMongoClient, TestProject", 
      "key": "eod" 
     } 
     ], 
     "parameters": { 
     "connectionString": "mongodb://localhost:27017/?readPreference=primary", 
     "database": "eod" 
     }, 
     "instanceScope": "single-instance" 
    }, 
    { 
     "type": "SimpleMongoClient, TestProject", 
     "services": [ 
     { 
      "type": "ISimpleMongoClient, TestProject", 
      "key": "live" 
     } 
     ], 
     "parameters": { 
     "connectionString": "mongodb://localhost:27017/?readPreference=primary", 
     "database": "live" 
     }, 
     "instanceScope": "single-instance" 
    } 
    ] 
} 

回答

4

要使用KeyFilter屬性,你需要註冊的東西做過濾with the WithAttributeFiltering()擴展。你不能通過配置來做到這一點。

+0

感謝您的澄清。你認爲如果值得通過配置使其可行嗎?我應該提出這個功能要求嗎? –

+0

不,配置不應該是與編程設置功能匹配的功能。如果您需要這樣做,推薦的解決方案是編寫帶有額外編程位的Autofac模塊並配置模塊。有關示例,請參閱文檔。 –