1

So here is the code:

using(var dbContext = contextFactory.GetContext())
{ 
     foreach(item in dbContext.Items)
     {
        try
        {
          var result = IRemoteWebService.SomeOperation(item);
        }
        catch(MyException e)
        {
             //assume that all possible exceptions are caught
        }
     }
}

Question: As far as I know the only possible problem in doing this is http call time-outs, which can be different for initial web request and web request made inside using DbContext. What are other possible disadvantages of doing this?

1
  • 2
    You mix code responsibilities which can be hard and complex to maintain and and to test Commented Feb 10, 2016 at 10:03

1 Answer 1

1

It is considered bad practice because you are mixing responsibilities. Your Database connection stays open while calling the HTTP service.

To make it more concrete: imagine a stall in the HTTP server and a high load on this particular function. In that case you'll have several DB connections open at the same time. This can cause unwanted side affects. For example Record locking (especially when you are also using write actions) or you could even hit your maximum DB-connection count.

A better approach would be to fetch the data first and than call your HTTP service. The code might look more like this:

List<Items> items = null;
using(var dbContext = contextFactory.GetContext())
{ 
     items = dbContext.Items.ToList(); //query all the items
}

//now loop the items
foreach(item in items )
{
    try
    {
        var result = IRemoteWebService.SomeOperation(item);
    }
    catch(MyException e)
    {
        //assume that all possible exceptions are caught
    }
}

It would be even better if you create sepperate methods, (put them in different classes even), for your data-query and http-call. This way you can reuse the code better and it's easier to maintain, more flexible en better testable.

As for a general note: it's best to keep things like connections (db, http, tcp/ip, filesystem etc.), graphics, locks, etc. open for the shortest time possible. There are of course performance optimization arguments which can argue this statement, but these are seldom valid since code complexity will increase at its cost.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.