I have a MVC 3 solution configured with Ninject using a repository pattern. Some of my bindings include:
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>().InRequestScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IMyRepository>().To<MyRepository>().InRequestScope();
kernel.Bind<IMyService>().To<MyService>().InRequestScope();
kernel.Bind<ILogging>().To<Logging>().InSingletonScope();
I also added a console application to my solution and I want to leverage the same repository and services. My Ninject configuration for the console application looks like:
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>().InSingletonScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InSingletonScope();
kernel.Bind<IMyRepository>().To<MyRepository>().InSingletonScope();
kernel.Bind<IMyService>().To<MyService>().InSingletonScope();
kernel.Bind<ILogging>().To<Logging>().InSingletonScope();
My console code looks like:
static void Main(string[] args)
{
IKernel kernel = new StandardKernel(new IoCMapper());
var service = kernel.Get<IMyService>();
var logger = kernel.Get<ILogging>();
... do some processing here
}
This works just fine but I want t be sure that I am configuring Ninject correctly for a console application. Is it correct to use InSingletonScope() for all my bindings in my console application? Should I be configuring it differently?
Do you want one and only one instance of each of your repository services for the whole application? If so, then use InSingletonScope.
Is your console application multithreaded? If this is the case and you want a new instance of your services for each thread then you will use InThreadScope.
If you want a new instance of the service(s) each time they are called for, set it to InTransientScope.
You also have the option of defining your own scope using InScope. Bob Cravens gives a good overview of each of these here http://blog.bobcravens.com/2010/03/ninject-life-cycle-management-or-scoping/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With