I have refactored away from the registry I used previously to store the DataAccessAdaptor, UnitOfWork, ServiceHome, etc. I am now using a DataContext class that has references to the other objects (DataAccessAdapterm etc.) but is itself managed by the DI container. So to access the DataAccessAdapter, instead of using
Registry.GetDataAccessAdapter();
you now use
ObjectFactory.GetInstance<IDataContext> ().Adapter;
All the connection and transaction management is now handled by the DataContext as well.
Here are some pieces of the DataContext class.
public class DataContext
: IDataContext
{
public ActionProcedures ActionProcedures { get; set; }
public IRetrievalProcedures RetrievalProcedures { get; set; }
public DataAccessAdapterBase Adapter { get; set; }
...
public void Clear ()
{
// If clear is called while there is still a transaction, the client code has a bug
if (Adapter != null && Adapter.IsTransactionInProgress)
{
throw new Exception ("There is still an active transaction.");
}
// First save any changes in UnitOfWork
if (UnitOfWork != null)
{
UnitOfWork.Commit (Adapter, true);
}
// Dispose and remove adapter
if (Adapter != null)
{
Adapter.Dispose ();
}
ActionProcedures = null;
RetrievalProcedures = null;
Adapter = null;
...
}
public void Initialize (
DataAccessAdapterBase adapter)
{
Adapter = adapter;
ActionProcedures = new ActionProcedures ();
RetrievalProcedures = new RetrievalProcedures ();
...
}
public virtual void StartTransaction (
IsolationLevel isolationLevel,
string transactionName)
{
Adapter.StartTransaction (isolationLevel, transactionName);
}
...
}The next step would now be to get rid of the DataAccessorHome and ServiceHome completely and simply get the data accessors and services from the DI container directly.
Thanks to Francois and Schalk for their inputs.