Tun
Tun

Reputation: 912

Shall I use using statement or dependency injection for web service client

I've recently written the a pieces of codes that involve Soap Web service call.

Example codes as below is perfectly working fine. The only problem is I couldn't do unit test the code as I use 'using' statement. I can use Constructor based Dependency Injection using MS Unity dependency injector.

The question is whether I shall use dependency injector for this or not. The reason of using 'Using' statement is I want to dispose the object after method called.

private ResultSet GetLookupMailingData()
    {
        try
        {
            using (var client = new NDataAccessSoapClient())
            {
                var result = client.GetLookupData(XMLLookupDataTypes.xldtMailings, "");
                return Deserialize<ResultSet>(result);
            }
        }
        catch (Exception)
        {
            return new ResultSet();
        }
    }

Upvotes: 1

Views: 1134

Answers (1)

Vladimir Petrov
Vladimir Petrov

Reputation: 143

You can use a factory that's injected instead. Thus you can mock the factory to return a mock client and setup expectations on that. For example:

interface INDataAccessSoapClientFactory
{
    NDataAccessSoapClient CreateClient();
}

class Lookup
{
    private INDataAccessSoapClientFactory factory;

    public Lookup(INDataAccessSoapClientFactory factory)
    {
        this.factory = factory;
    }

    private ResultSetGetLookupMailingData()
    {
        try
        {
            using (var client = factory.CreateClient())
            {
                var result = client.GetLookupData(XMLLookupDataTypes.xldtMailings, "");
                return Deserialize<ResultSet>(result);
            }
        }
        catch (Exception)
        {
           return new ResultSet();
        }
    }
}

Upvotes: 1

Related Questions