Using the factory method overload seems suitable use case for it.
services.AddScoped<IDocumentIntegration>(provider => {
var client = new DocumentIntegrationClient();
// Use configuration object to read it from appconfig.json
client.ClientCredentials.UserName.UserName = Configuration["MyService:Username"];
client.ClientCredentials.UserName.Password = Configuration["MyService:Password"];
client.Endpoint.Address = new EndpointAddress(Configuration["MyService:BaseUrl"]);
return client;
});
Where your appsettings would look like
{
...
"MyService" :
{
"Username": "guest",
"Password": "guest",
"BaseUrl": "http://www.example.com/"
}
}
Alternatively, inject the Options via options pattern. Since the DocumentIntegrationClient
is partial, you can create a new file and add a parameterized constructor.
public partial class DocumentIntegrationClient :
System.ServiceModel.ClientBase<ServiceReference1.IDocumentIntegration>, ServiceReference1.IDocumentIntegration
{
public DocumentIntegrationClient(IOptions<DocumentServiceOptions> options) : base()
{
if(options==null)
{
throw new ArgumentNullException(nameof(options));
}
this.ClientCredentials.Username.Username = options.Username;
this.ClientCredentials.Username.Password = options.Password;
this.Endpoint.Address = new EndpointAddress(options.BaseUrl);
}
}
And create a options class
public class DocumentServiceOptions
{
public string Username { get; set; }
public string Password { get; set; }
public string BaseUrl { get; set; }
}
and populate it from appsettings.json
.
services.Configure<DocumentServiceOptions>(Configuration.GetSection("MyService"));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…