0

I have a class in c# that takes in 2 parameters: dependency on MongoDB database and a string variable denoting the name of the collection in the DB. How can I register this class in Program.cs?

My MongoRepository class:

namespace Play.Catalog.Service.Repositories
{
    public class MongoRepository<T> : IRepository<T> where T: IEntity
    {
        private readonly IMongoCollection<T> dbCollection;

        private readonly FilterDefinitionBuilder<T> filterBuilder = Builders<T>.Filter;

        public MongoRepository(IMongoDatabase database, string collectionName)
        {
            dbCollection = database.GetCollection<T>(collectionName);
        }
...
}

I am using .net6

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
  • Possible duplicate of https://stackoverflow.com/questions/34834295/dependency-injection-inject-with-parameters – Nahid Dec 30 '22 at 05:14
  • @Nahid In that question there's only a string as a parameter, but in my case I also have a DI in the `MongoRepository` class which makes it difficult to call this cass from `Program.cs`. – Shivam Kumar Singh Dec 30 '22 at 07:06

1 Answers1

1

Something like that:

services.AddSingleton<IMyService>(conf => 
new MyService(conf.GetRequiredService<IMongoDatabase>(),
configuration.GetValue<string>("CollectionName")));
Maruf
  • 354
  • 3
  • 8