How to inject a changing dependency

I'm new to dependency injection, I'm wondering how you would handle the following scenario. We have something like the following:

public class DatabaseContext
{
  public string ConnectionString {get;}
}

public interface IDataAccess
{
  string GetString(int id);
}

public class DataAccessImpl : IDataAccess
{
  private DatabaseContext _context;
  public DataAccessImpl(DatabaseContext context)
  {
    this._context=context;
  }

  public string GetString(int id)
  {
    return "some data";
  }
}

      

For web applications, each request can create a different DatabaseContext to point to a different database. For windowed forms, we can change the current DatabaseContext. How does the di framework handle a dependency that might change? This way, when I ask for IDataAccess, it always has the corresponding / current DatabaseContext.

+1


source to share


1 answer


The approach I have taken is not to inject the DataContext, but in the DataContext factory, a class with a method that returns a DataContext of the appropriate type. I have two constructors, for my controller class - a default constructor and one that accepts a factory (and other injected objects). The default constructor simply calls the parameterized constructor with all parameters null. The parameterized constructor creates default objects if the corresponding parameter is null.

Using a factory allows my controller actions to create a new DataContext when called, instead of a single DataContext that exists for the lifetime of the application. A factory can be built to return an existing context if available and create a new one as needed, but I prefer to combine them into a unit of work.



The PS factory actually creates a wrapper class around the DataContext, not the actual DataContext like an interface (IDataContextWrapper). This makes it much easier to mock the actual database from my controller tests. All of the above assumes LINQ / ASP.NET MVC, but the principles generally apply I think.

+1


source







All Articles