使用附加属性注入ToMethod()?

问题描述 投票:1回答:1

我正在注入一个RestSharp IRestClient实例来进行API调用:

kernel.Bind<IRestClient>()
      .ToMethod(context => new RestClient("http://localhost:63146/api/"));

但是,我还需要使用HttpBasicAuthenticator进行身份验证。我目前正在注射这样的IAuthenticator

kernel.Bind<IAuthenticator>()
      .ToMethod(context => new HttpBasicAuthenticator("user", "password"));

有没有办法将两者结合起来,以便我只需要注入IRestClient并且默认情况下附加了身份验证器?

例如,我尝试过类似的东西:

kernel.Bind<IRestClient>()
      .ToMethod(context => 
          new RestClient("http://localhost:63146/api/")
               .Authenticator = new HttpBasicAuthenticator("user", "password"));

但这不是编译。

c# ninject
1个回答
1
投票

ToMehtod采用常规Func<IContext, T>,您不仅限于简单的对象创建,但您可以编写任何指定的复杂函数。

因此,您可以轻松地将两个调用与:

kernel.Bind<IRestClient>()
    .ToMethod(context => {
        var client = new RestClient("http://localhost:63146/api/");
        client.Authenticator = new HttpBasicAuthenticator("user", "password");
        return client;
    });
© www.soinside.com 2019 - 2024. All rights reserved.