Vyas Rao Vyas Rao - 1 month ago 16
C# Question

Generic Unit Of Work

I have implemented EntityFramework pattern along with Repository and Unit Of Work. The implementation is similar to Code Project Repository Example, however I need an enhancement for the Unit Of Work.

The unit of work

public class GenericUnitOfWork : IDisposable
{
// Initialization code

public Dictionary<Type, object> repositories = new Dictionary<Type, object>();

public IRepository<T> Repository<T>() where T : class
{
if (repositories.Keys.Contains(typeof(T)) == true)
{
return repositories[typeof(T)] as IRepository<T>
}
IRepository<T> repo = new Repository<T>(entities);
repositories.Add(typeof(T), repo);
return repo;
}

// other methods
}


The above UoW is quiet generalized and it targets the parent Repository class always. I have another entity, for example student, which has its own repository extending the Repository class. The student specific repository has a method "GetStudentMarks()". Now I cannot use the general Unit Of Work class since it always points to the parent Repository.

How to implement a general Unit Of Work to handle such situations? Thanks in advance.

Answer

You can make the class GenericUnitOfWork generics, specifying the entity and repository type:

public class GenericUnitOfWork<TRepo, TEntity> : IDisposable
    where TRepo : Repository<TEntity>
{
    // Initialization code

    public Dictionary<Type, TRepo> repositories = new Dictionary<Type, TRepo>();

    public TRepo Repository()
    {
        if (repositories.Keys.Contains(typeof(TEntity)) == true)
        {
            return repositories[typeof(TEntity)];
        }
        TRepo repo = (TRepo)Activator.CreateInstance(
            typeof(TRepo),
            new object[] { /*put there parameters to pass*/ });
        repositories.Add(typeof(TEntity), repo);
        return repo;
    }

    // other methods
}

Something like this should works.

Comments