0
votes

I'm new to dependency injection in .net core. So far i was using interface and was easily able to inject dependencies via DI framework.

Now, I have one external library which holds mongo DB connection and provides necessary database operation calls.

The class accepts two parameters i.e connection string and database name. As MOQ can inject dependency without interface so i tried to add below code

services.AddSingleton<MongoManager>();

As MongoManager Class accepts connection string so this would not work. After this tried below code.

services.AddSingleton(new MongoManager(userName, database));

Above code works as expected however it creates object at the time of app start. In other cases .net framework gives instance of a class when its first time requested, however here its getting created without being asked by app anywhere. Also would this object be disposed when app terminates? Is there any way to register classes and tell the framework to pass certain arguments like connection string, database Name etc. to the class when the instance requested first time.

2

2 Answers

1
votes

There is an overload that accepts Func<IServiceProvider, TService> which will only instantiate the singleton when first required:

services.AddSingleton(_ => new MongoManager(userName, database));
1
votes

You can control the scope by using services.AddTransient or service.AddScoped.

All will be disposed of when the application will terminate.

Sorry, I misunderstood your question, you can pass the parameters to the method like this.

services.AddSingleton(x => new MongoManager(param1, param2));

Singleton lifetime services (AddSingleton) are created the first time they're requested (or when Startup.ConfigureServices is run and an instance is specified with the service registration).

In apps that process requests, singleton services are disposed of when the ServiceProvider is disposed of at the app shutdown.

Reference: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#singleton