为控制台应用程序配置Ninject并为我的MVC应用程序利用现有存储库 [英] Configuring Ninject for a console application and leveraging the existing repository for my MVC application
问题描述
我有一个使用存储库模式配置了Ninject的MVC 3解决方案.我的一些绑定包括:
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();
我还向我的解决方案添加了一个控制台应用程序,我想利用相同的存储库和服务.控制台应用程序的Ninject配置如下:
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();
我的控制台代码如下:
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
}
这很好用,但是我不确定我是否为控制台应用程序正确配置了Ninject.对控制台应用程序中的所有绑定使用InSingletonScope()是否正确?我应该以不同的方式配置它吗?
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?
推荐答案
对于整个应用程序,您是否需要每个存储库服务的一个且只有一个实例?如果是这样,则使用InSingletonScope.
Do you want one and only one instance of each of your repository services for the whole application? If so, then use InSingletonScope.
您的控制台应用程序是多线程的吗?如果是这种情况,并且您希望每个线程都有一个新的服务实例,那么您将使用InThreadScope.
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.
如果每次都需要服务的新实例,请将其设置为InTransientScope.
If you want a new instance of the service(s) each time they are called for, set it to InTransientScope.
您还可以选择使用InScope定义自己的范围.鲍勃·克雷文斯(Bob Cravens)在这里 http://://blog.bobcravens.com/2010/03/ninject-life-cycle-management-or-scoping/
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/
这篇关于为控制台应用程序配置Ninject并为我的MVC应用程序利用现有存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!