I am trying to figure out how to use IoC in situations where the dependent classes can change based on some variable in the application (in this case, Session state). For example, each of our clients have a different database, so the connection to the database needs to be built on a value stored in their Session (particularly since some users could have multiple databases if they own multiple businesses, and would switch between databases).
Here is a generic example of how we'd currently set up this structure:
public class MyTestController : ControllerBase
{
Repository _rep;
public MyTest(Repository rep)
{
_rep = rep;
}
public MyTest()
{
string connString = String.Format("Server={0}; Database={1};"
, SessionContainer.ServerName, SessionContainer.DatabaseName;
var dc = new DataContext(connString);
_rep = new Repository(dc);
}
public int SampleFn()
{
return _rep.GetCountOfEmployees();
}
}
public class Repository
{
DataContext _context;
public Repository(DataContext context)
{
_context = context;
}
}
Would we be able to set this up using IoC and eliminate the default c-tors? If so, how? I don't have a problem just using D.I. like this, but I'd like to explore the possibility of a StructureMap or Unity (note: we normally pass in db/server to a factory class that builds the datacontext ... above example is just for brevity).