具有KeyFilter属性的构造函数的Autofac配置

时间:2017-04-26 14:06:29

标签: json configuration autofac

我正在尝试使用Autofac配置来创建服务对象。

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"
    }
  ]
}

1 个答案:

答案 0 :(得分:6)

要使用KeyFilter属性,您需要注册执行过滤with the WithAttributeFiltering()扩展的内容。你不能通过配置来做到这一点。