开发者

Configuring Ninject for a console application and leveraging the existing repository for my MVC application

I have a MVC 3 solution configured with Ninject using a repository pattern. Some of my bindings include:

开发者_C百科
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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜