Dependency Injection for IRepository<T>

Feb 19, 2014 at 3:41 PM
Hi,

I really like the look of this IRepository solution and was having a play but I have one question.

Is it possible to inject the IRepository<T> class at the point it is created inside the UnitOfWork, rather than being hard coded to the Repository<T>?

I have been trying but not been able to find a way to do it?

Cheers.
Coordinator
Feb 20, 2014 at 9:59 AM
I not sure where we've hard coded anything in UnitOfWork.cs, however, we are using Activation to new an instance during run-time, if that's what your referring to. You can't have this injected, however you can leverage IoC for this, just make sure you have your registrations wired up in UnityConfig for all your repositories.

Before (implemented with Activation):
        public IRepositoryAsync<TEntity> RepositoryAsync<TEntity>() where TEntity : EntityBase
        {
            return ServiceLocator.Current.GetInstance<IRepositoryAsync<TEntity>>();
            if (_repositories == null)
            {
                _repositories = new Hashtable();
            }

            var type = typeof (TEntity).Name;

            if (_repositories.ContainsKey(type))
            {
                return (IRepositoryAsync<TEntity>) _repositories[type];
            }

            var repositoryType = typeof (Repository<>);
            _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof (TEntity)), _context));

            return (IRepositoryAsync<TEntity>) _repositories[type];
        }
After (IoC with ServiceLocator Pattern)
        public IRepositoryAsync<TEntity> RepositoryAsync<TEntity>() where TEntity : EntityBase
        {
            return ServiceLocator.Current.GetInstance<IRepositoryAsync<TEntity>>();
        }
Marked as answer by lelong37 on 3/31/2014 at 10:26 PM