web-dev-qa-db-ja.com

ASP.NetコアにWCFサービスクライアントを挿入する方法

ASP.NET Coreからアクセスする必要があるWCFサービスがあります。 WCF Connected Preview をインストールし、プロキシを正常に作成しました。

以下のようなインターフェースとクライアントを作成しました

    [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "0.3.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference1.IDocumentIntegration")]
    public interface IDocumentIntegration
    {

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IDocumentIntegration/SubmitDocument", ReplyAction="http://tempuri.org/IDocumentIntegration/SubmitDocumentResponse")]
        [System.ServiceModel.FaultContractAttribute(typeof(ServiceReference1.FaultDetail), Action="http://tempuri.org/IDocumentIntegration/SubmitDocumentFaultDetailFault", Name="FaultDetail", Namespace="http://schemas.datacontract.org/2004/07/MyCompany.Framework.Wcf")]
        System.Threading.Tasks.Task<string> SubmitDocumentAsync(string documentXml);
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "0.3.0.0")]
    public interface IDocumentIntegrationChannel : ServiceReference1.IDocumentIntegration, System.ServiceModel.IClientChannel
    {
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "0.3.0.0")]
    public partial class DocumentIntegrationClient : System.ServiceModel.ClientBase<ServiceReference1.IDocumentIntegration>, ServiceReference1.IDocumentIntegration
    { 
      // constructors and methods here
    }

サービスを呼び出すコンシューマークラスは次のようになります。

public class Consumer
{
  private IDocumentIntegration _client;
  public Consumer(IDocumentIntegration client)
  {
    _client = client;
  }

  public async Task Process(string id)
  {  
     await _client.SubmitDocumentAsync(id);
  }
} 

スタートアップクラスのConfigureServicesメソッドにIDocumentIntegrationを登録するにはどうすればよいですか?登録時にRemoteAddressとclientCredentialsをセットアップしたい

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddMvc();

        // how do I inject DocumentIntegrationClient here??
        var client = new DocumentIntegrationClient();            
        client.ClientCredentials.UserName.UserName = "myusername";
        client.ClientCredentials.UserName.Password = "password";
        client.Endpoint.Address = new EndpointAddress(urlbasedonenvironment)

    }
10
LP13

ファクトリメソッドオーバーロードの使用は、適切なユースケースのようです。

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;
});

アプリの設定は次のようになります

{
    ...
    "MyService" : 
    {
        "Username": "guest",
        "Password": "guest",
        "BaseUrl": "http://www.example.com/"
    }
}

または、オプションパターンを使用してオプションを挿入します。 DocumentIntegrationClientは部分的であるため、新しいファイルを作成し、パラメーター化されたコンストラクターを追加できます。

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);
    }
}

そして、オプションクラスを作成します

public class DocumentServiceOptions
{
    public string Username { get; set; } 
    public string Password { get; set; }
    public string BaseUrl { get; set; }
}

appsettings.json

services.Configure<DocumentServiceOptions>(Configuration.GetSection("MyService"));
22
Tseng