2

Is there anything wrong with me using InSingletonScope() for the database context in a console application? I am running through a loop and running a job for each item. Would another scope be better? I usually use RequestScope if I am using Ninject in a web application.

static void Main(string[] args)
{
    IKernel kernel = new StandardKernel();

    kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>()
        .InSingletonScope();
Steven
  • 166,672
  • 24
  • 332
  • 435
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

2 Answers2

3

It depends if your console app is multi-threaded. If so, you should use InThreadScope so the IDisposable objects will be disposed at the end of the thread. If not, you can stay with InSingletonScope it would make no difference that you would use InThreadScope in singlethread app.

If you have some extra demand on scoping, you can try custom scope InScope. Or you can try ninject named scope extensions.

Similar question here: Configuring Ninject for a console application and leveraging the existing repository for my MVC application

Community
  • 1
  • 1
mipe34
  • 5,596
  • 3
  • 26
  • 38
  • This worked, but after using it noticed it was putting my database in a suspended state as the singleton on my databasefactory was holding up the database. – Mike Flynn Jan 16 '16 at 21:48
0

It's all about 'requests'. Each application handles requests and each request should get its own scope. If your console application just handles one request (it processes command line arguments, executes some business logic and dies) a singleton scope is fine. If your application lives for a long time and handles many requests (as the use of jobs might be suggesting) it's propably best to see each job (or optionally a group of jobs) as one request.

Within web applications the the request is usually a web request and the scope is usually around one HTTP request. For WCF services the request is one WCF operation and the scope is around that operation. For Windows services there is no such thing as HTTP or WCF operation, and you usually use something called a 'lifetime scope' (a lifetime that you explicitly begin and end).

I don't know what the exact terminology is for Ninject, but you probably need something like a lifetime scope.

Steven
  • 166,672
  • 24
  • 332
  • 435