I seem to be having trouble finding a way to cast & return an Activator-created instance as its generic type. I have looked at various examples...but cannot seem to find an "exact" example for what I am trying to accomplish.
- How do I return the correct type from the GetRepositoryInstance method below?
For instance...
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
}
public class TransactionProvider : ITransactionProvider
{
public void AddPending(ITransaction transaction)
{
// Get the targeted types
var typeEntity = GetTransactionEntityType(transaction.EntityName);
var typePendingEntity = GetTransactionPendingEntityType(transaction.EntityName);
// Get the Repository Instances for each type
var repositoryEntity = GetRepositoryInstance(typeEntity);
var repositoryPendingEntity = GetRepositoryInstance(typePendingEntity);
}
// -----
// HERE...I want to return the generated type as its' IRepository<>...how?
// -----
private IRepository<> GetRepositoryInstance(Type entity)
{
var repositoryType = typeof(GenericRepository<>).MakeGenericType(entity);
var repository = Activator.CreateInstance(repositoryType);
return repository;
}
}
Aucun commentaire:
Enregistrer un commentaire