vendredi 19 novembre 2021

How to inject a IEnumerable

I don't no which pattern this is, but I want to accomplish to add an IEnumerable of multiple classes which uses DI also. In my example I want to inject the IEnumerable in the BaseRepository, filled with the Custom2Repository and Custom2Repository classes which have this ICustomRepository interface and uses also injection. Can anybody help me in the right direction?

 public class BaseRepository : IBaseRepository //This is the main class
 {
        private readonly IProvider _provider;
        private readonly DbContext _dbContext;
        private readonly IEnumerable<ICustomRepository> _customRepositories;
        private string _databaseName;

        public BaseRepository(IProvider provider, DbContext dbContext, **IEnumerable<ICustomRepository> customRepositories**)
        {
            _provider = provider;
            _dbContext = dbContext;
            _customRepositories = customRepositories;
        }

        public async Task ChangeAsync(string id, CancellationToken cancellationToken)
        {
            var tracker = _provider.Get();
            var change = tracker.GetChange(id);
            foreach (var repo in **_customRepositories**)
                if (repo.EntityName == change.EntityName)
                {
                    _databaseName = repo.DatabaseName;
                    repo.Method1(id, cancellationToken)
                }
            await tracker.SaveChangesAsync(_databaseName, cancellationToken);
        }
...
 }

public class Custom1Repository : ICustomRepository //This I want to inject the base IEnumerable in the baseRepository
{
        public Custom1Repository(IProvider provider, ITracker tracker, DbContext dbContext)
        {
            _provider = provider;
            _tracker = tracker;
            _dbContext = dbContext;
        }

        public string EntityName => "EntityOne";
        public string DatabaseName { get; private set; }
        public async Task Method1Async(string id, CancellationToken cancellationToken)
...
}
public class Custom2Repository : ICustomRepository //This I want to inject the base IEnumerable in the baseRepository too
{
        public Custom2Repository(IProvider provider, ITracker tracker, DbContext dbContext)
        {
            _provider = provider;
            _tracker = tracker;
            _dbContext = dbContext;
        }

        public string EntityName => "EntityTwo";
        public string DatabaseName { get; private set; }
        public async Task Method1Async(string id, CancellationToken cancellationToken)
...
}

Aucun commentaire:

Enregistrer un commentaire