When to use Singleton vs Transient vs Request using Ninject and MongoDB

Viewed 16489

I'm not quite sure when I should use SingletonScope() vs TransientScope() vs RequestScope() when I do my binding in my global.cs file.

I have for example my call to MongoSession (using NoRM and the mvcStarter project http://mvcstarter.codeplex.com/) which is set to SingletonScope but I created a repository that use this MongoSession object to make calls to Mongo easier, e.g., I have a NewsRepository which uses MongoSession to fetch my News items from the data. As an example I have a call that fetches News items that has DisplayOnHome set to true and get the latest by CreationDate. Should such a repository be SingletonScope or would RequestScope would be more appropriate?

When should I use each of it and why?

4 Answers

I am having this issue too, Lately, I started working on MongoDB. MongoDB recommends singleton for MongoClient. So I am still not sure about my implementation, and I am confused. I implemented the Mongo in the DI container two ways, and I am not sure which one is good. Let's take the first approach

  1. Here I return a singleton instance of IMongoClient

    services.AddSingleton(_ => { return new MongoClient(con.ConnectionString); });

Then,

services.AddScoped<IMongoDatabase>(s =>
                {
                    var client = p.GetRequiredService<IMongoClient>();
                    return client.GetDatabase(con.DatabaseName);
                });

Then, return a scoped for my IMongoDatabase. In my repo, I inject the IMongoDatabaseand then call my DB.

    _dataContext = mongoDBClient.GetCollection<SomeCollection>(GetCollectionNameFromAppSetting((settings.DPUBotCollectionName)));

The second one I was returning an IMongoDatabase as a singleton:

services.AddSingleton<IMongoDatabase>(_ =>
            {
                //var connectionString = con;

                return new 
         MongoClient(con.ConnectionString).GetDatabase("SomeDatabase");
            });

Monog says their MonogClient and IMongoDatabase are thread-safe. I am not sure which approach is right. I would appreciate it if you could give me an answer.

Related