向 ToMethod() 注入额外的 属性?
Inject ToMethod() with additional property?
我正在注入一个 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"));
但这不是编译。
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;
});
我正在注入一个 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"));
但这不是编译。
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;
});