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

女生的网名这么多〃 提交于 2019-12-30 00:57:11

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/6627827/configuring-ninject-for-a-console-application-and-leveraging-the-existing-reposi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!