Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created February 5, 2013 14:20
Show Gist options
  • Select an option

  • Save jarrettmeyer/4714731 to your computer and use it in GitHub Desktop.

Select an option

Save jarrettmeyer/4714731 to your computer and use it in GitHub Desktop.
When to use statics in C#. I'm sure there are other examples, but these are always valid.
// There are three times when I will openly use static methods in C#.
// 1. Providers
// 2. State Machines (variation on provider, really)
// 3. Any time where there *really* is *one* of something.
/// <summary>
/// 1. Providers give you a way to create new objects without using a constructor. Ideally, you would always
/// use Dependency Injection and Inversion of Control. However, these techniques do not work in all situations,
/// so we need a testable fallback. Providers fill this need.
/// </summary>
public class ConnectionProvider
{
private static IDbConnection testConnection;
public static IDbConnection GetConnection(/* there might be params here */)
{
if (HasTestConnection)
return testConnection;
// You might have logic here in how you build a DB connection instance,
// especially if you have multiple databases, etc.
// Snip
return connection;
}
public static void ResetTestConnection()
{
testConnection = null;
}
public static void ConfigureTestConnection(IDbConnection dbConnection)
{
if (dbConnection == null)
throw new ArgumentNullException("dbConnection");
testConnection = dbConnection;
}
private static bool HasTestConnection
{
get { return testConnection != null; }
}
}
// In your runtime, instead of using
//
// var connection = new SqlConnection("connection string");
// or
// var connection = new OracleConnection("connection string");
//
// you will instead use
//
// var connection = ConnectionProvider.GetConnection();
//
// In your test, you will need a setup. This could point to a SQLite in-memory database, a
// shared test DB, a Mock/Stub, whatever.
//
// [TestSetup]
// public void before_each_test()
// {
// IDbConnection fakeConnection = ...;
// ConnectionProvider.ConfigureTestConnection(fakeConnection);
// }
//
// [TestTearDown]
// public void after_each_test()
// {
// ConnectionProvider.ResetTestConnection();
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment