In the WebAPIConfig.cs file, register the repository with the Unity Container. This code file defines the delegate where you should put your Web API configuration code. Install the Unity Nuget package in your Project.
var container = new Unity.UnityContainer();
// this will register all Repositories that implement Repository<>.
// because of the generics, you have to use the concrete type not the interface for injection
container.RegisterType(typeof(IRepository<>), typeof(Repository<>), new HierarchicalLifetimeManager());
Define the Repository interface:
public interface IRepository
{
bool Exists(int id);
IQueryable GetAll();
TEntity Get(int id);
}
Create the Abstract class for the Repository. The LogManager is for the log4net implementation for logging.
public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected Models.DBEntities db = new Models.DBEntities();
private DbContextTransaction Transaction { get; set; }
protected static ILog log;
public abstract TEntity Get(int id);
public abstract IQueryable<TEntity> GetAll();
public Repository<TEntity> BeginTransaction()
{
Transaction = db.Database.BeginTransaction();
return this;
}
public abstract bool Exists(int id);
// select specific columns into a DTO using specified selector
//
public abstract TResult Get<TResult>(int id, Expression<Func<TEntity, TResult>> selector);
public abstract List<TResult> GetAll<TResult>(Expression<Func<TEntity, TResult>> selector);
public Repository()
{
// setup the logger from the instance so we can get the derived type
log = LogManager.GetLogger(this.GetType()); // should log as the derived type
db.Configuration.LazyLoadingEnabled = false;
setDBLogging();
}
public void logdb(string msg)
{
if (ConfigurationManager.AppSettings["LogDB"] == "true")
{
try
{
log.Debug(msg.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty));
}
catch (Exception ex)
{
log.Error("failed logging DB activity", ex);
}
}
}
public void setDBLogging()
{
if (ConfigurationManager.AppSettings["LogDB"] == "true")
{
try
{
db.Database.Log = msg => logdb(msg);
}
catch (Exception ex)
{
log.Error("failed setting up DB logging", ex);
}
}
}
}
Example Users Respository with a transaction:
using DBMODELS = ApiPersistence.Models;
public class UsersRepository : Repository<DBMODELS.user>
{
public override bool Exists(int id)
{
throw new System.NotImplementedException();
}
public override DBMODELS.user Get(int id)
{
try
{
IQueryable<DBMODELS.user> query = from user in db.users
where user.id == id
select user;
var userObj = query.FirstOrDefault();
return userObj;
}
catch (Exception ex)
{
throw ex;
}
}
public override IQueryable<DBMODELS.user> GetAll()
{
throw new NotImplementedException();
}
public UserDTO CreateUser(){
//Example transaction:
using (var transaction = db.Database.BeginTransaction())
{
try
{
///code for creating user goes here...
db.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
log.Error("caught exception", ex);
throw new RepositoryException("CreateMethod()", "MyRepository CreateMethod() failed", ex);
}
}
}
}