3
\$\begingroup\$

I'm giving the repository + UoW patterns my first shot on the server side, so bear with me. Also, it's worth mentioning that I haven't used an IoC container on the server side before either, so I'll post its setup too. I'm using simple injector at the moment.

All kinds of feedback is appreciated, especially for UnitOfWork.GetRepository<T>() a bit below, which I'm not very satisfied with.

var container = new Container();

container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

container.Register(typeof(IUnitOfWork), typeof(UnitOfWork), Lifestyle.Scoped);

container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

container.Verify();

GlobalConfiguration.Configuration.DependencyResolver = 
                                     new SimpleInjectorWebApiDependencyResolver(container);
public interface IUnitOfWork
{
    DatabaseRepository<T> GetRepository<T>() where T : BaseEntity;
    Task CommitAsync();
}
public class UnitOfWork : IUnitOfWork, IDisposable
{
    private readonly Entities _context = new Entities();
    private readonly IDictionary<Type, object> _repositories = new Dictionary<Type, object>();

    public DatabaseRepository<T> GetRepository<T>() where T : BaseEntity
    {
        var type = typeof(T);

        if (!_repositories.ContainsKey(type))
        {
            var instance = (DatabaseRepository<T>)Activator.CreateInstance(typeof(DatabaseRepository<T>), _context);
            _repositories[type] = instance;
        }

        return _repositories[type] as DatabaseRepository<T>;
    }

    public async Task CommitAsync()
    {
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbEntityValidationException e)
        {
            // todo: handle validation errors...
            throw;
        }
    }

    private bool _disposed;

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.