Repository pattern - make it testable, DI and IoC friendly and IDisposable
<p>What I have:</p>

<pre><code>public interface IRepository
{
   IDisposable CreateConnection();
   User GetUser();
   //other methods, doesnt matter
}

public class Repository
{
   private SqlConnection _connection;

   IDisposable CreateConnection()
   {
      _connection = new SqlConnection();
      _connection.Open();
      return _connection;
   }

   User GetUser()
   {
      //using _connection gets User from Database
      //assumes _connection is not null and open
   }
   //other methods, doesnt matter 
}
</code></pre>

<p>This enables classes that are using IRepository to be easily testable and IoC containers friendly. However someone using this class has to call CreateConnection before calling any methods that are getting something from database, otherwise exception will be thrown. This itself is kind of good - we dont want to have long lasting connections in application. So using this class I do it like this.</p>

<pre><code>using(_repository.CreateConnection())
{
    var user = _repository.GetUser();
    //do something with user
}
</code></pre>

<p>Unfortunetelly this is not very good solution because people using this class (including even me!) often forget to call <code>_repository.CreateConnection()</code> before calling methods to get something from database.</p>

<p>To resolve this I was looking at Mark Seemann blog post <a href="http://blog.ploeh.dk/2016/06/15/sut-double/" rel="noreferrer">SUT Double</a> where he implements Repository pattern in correct way. Unfortunately he makes Repository implement IDisposable, which means I cannot simply inject it by IoC and DI to classes and use it after, because after just one usage it will be disposed. He uses it once per request and he uses ASP.NET WebApi capabilities to dispose it after request processing is done. This is something I cannot do because I have my classes instances which use Repository working all the time.</p>

<p>What is the best possible solution here? Should I use some kind of factory that will give me IDisposable IRepository ? Will it be easily testable then?</p>