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(
IRepo开发者_运维技巧sitory<Organization> organizationRepository)
{
this.organizationRepository = organizationRepository;
}
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.
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.
精彩评论