3

is it ok to use something like this in the web: (my application is on asp.net mvc)

public static class DbUtil
{  
      public static int Insert(object o, string cs)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
              ...

                conn.Open();
                return Convert.ToInt32(cmd.ExecuteScalar());
            }
        }
}

usage:

public class Repository<T> : IRepository<T>
{
       public virtual int Insert(T o)
       {
            return DbUtil.Insert(o, Cs);
       }
}

and after constructor injection in the service or controller

    public MyController(
        IRepository<Organization> organizationRepository)
    {
        this.organizationRepository = organizationRepository;
    }
1
  • This totally depends on how you call this method. Can you give us examples of its usage? Otherwise it's impossible to say anything useful about it.
    – Steven
    Oct 4, 2010 at 13:06

2 Answers 2

2

It is absolutely OK to use this static class as long as it is hidden and wrapped behind the repository as it is in your case. This allows weaker coupling between the controller logic using the repository and the data access. The static method you've shown seems perfectly reentrant which makes it thread safe.

4
  • ok, also my IoC does a singleton by default for each Repository, is it ok in the web ?
    – Omu
    Oct 4, 2010 at 13:23
  • Yes, as long as your repositories are reentrant and thread safe. But be extremely careful if you use a custom controller factory: static controllers might destroy everything :-) On the other hand I prefer to keep even my repositories non-singleton to avoid someone messing up with the code and making it non thread-safe. Quite frankly the price of object instantiation is negligible compared to the usage. Oct 4, 2010 at 13:24
  • well, you saw my repository, it's just raw ado.net, no calls to lock or anything, it this thread safe ?
    – Omu
    Oct 4, 2010 at 13:26
  • @Omu, I've saw only a small code snippet which as I stated in my answer is perfectly thread-safe. I cannot draw conclusions for your repositories in general as I haven't seen them. Oct 4, 2010 at 13:27
1

As written, your static method has no concurrency issues, since it doesn't operate on any shared data, and each invocation instantiates its own local connection and command objects.

However, it doesn't really seem you are gaining much from making the method static. In general you should prefer instance methods over static methods since static method calls cannot be mocked out during testing.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.