Creating DbFactory

In an enterprise application, we may have multiple databases from where we need to perform database operations. So, rather than injecting DataContext directly into the Repository, we will create a DbFactory class and inject our DataContext through dependency injection. For example, if we have multiple data context classes pointing to different databases, we can inject them all through the parameterized constructor in DbFactory and expose properties to return their instance.

It is always better to expose interfaces, as it encapsulates the actual implementation. We will create the IDbFactory interface and then implement it using the DbFactory class.

Here is the code of the  IDbFactory interface:

    public interface IDbFactory 
{
DataContext GetDataContext { get; }
}

The following is the code of the DbFactory class:

    public class DbFactory : IDbFactory, IDisposable 
{

private DataContext _dataContext;
public DbFactory(DataContext dataContext)
{
_dataContext = dataContext;
}

public DataContext GetDataContext
{
get
{
return _dataContext;
}
}

#region Disposing

private bool isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

public void Dispose(bool disposing)
{
if (!isDisposed && disposing)
{
if (_dataContext != null)
{
_dataContext.Dispose();
}
}
isDisposed = true;
}

#endregion
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.139.42