First i am reading this article.He uses a custom in memory repository for testing and proof of concept reason. RepositoryEntityStore .
Then in order to avoid the use of new he implements this which isnt included in article but in sample.
namespace eDirectory.Naive.Repository
{
/// <remarks>
/// version 0.2 Chapter II: Repository
/// </remarks>
public class RepositoryLocatorEntityStore
: RepositoryLocatorBase
{
protected Dictionary<Type, object> RepositoryMap = new Dictionary<Type, object>();
public override IRepository<T> GetRepository<T>()
{
var type = typeof(T);
if (RepositoryMap.Keys.Contains(type)) return RepositoryMap[type] as IRepository<T>;
var repository = new RepositoryEntityStore<T>();
RepositoryMap.Add(type, repository);
return repository;
}
}
}
Later i think that he uses DI to not even create instance of RepositoryEntityStore .
The question is how can i modify this in order to work with classes that extend RepositoryEntityStore ? Like CustomerRepositoryEntityStore ?
If you don’t really know in advance (or don’t want to know, as part of DI) the exact type, you could use
Activator.CreateInstance(typeof(T))You will still have to make sure your type provide a default constructor
new()In order to provide that kind of flexibility, you will need to use an IoC (Inversion of Control) container, that will contain either the mapping or some logic to determine which dependency to use when instantiating your object.
This can be achieved through some external component such as ninject or it can be as simple as a config files that generates a mapping between types and assemblies.
Then, since you are using generic classes, you will need to
Makethe right (computed) type. This command takes care of this :MakeGenericType(type)You will then be able to create the instance of this generated type.
So your code would look like :