How to inject WCF service client in ASP.Net core?

后端 未结 1 979
粉色の甜心
粉色の甜心 2020-12-13 21:54

I have WCF service that I need to access from ASP.NET Core. I have installed WCF Connected Preview and created proxy successfully.

It created interface & client

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 22:31

    Using the factory method overload seems suitable use case for it.

    services.AddScoped(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
    {
        public DocumentIntegrationClient(IOptions 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(Configuration.GetSection("MyService"));
    

    0 讨论(0)
提交回复
热议问题