我可以使用Ninject实例化不依赖任何内容的单例服务吗? [英] Can I use Ninject to instantiate singleton services that nothing depends on?

查看:79
本文介绍了我可以使用Ninject实例化不依赖任何内容的单例服务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的asp.net mvc应用程序中有一些服务,它们侦听AMQP消息并调用方法.

I have some services in my asp.net mvc application that listen for AMQP messages and invoke methods.

没有控制器依赖于此,因此不会单独实例化它.

No controllers depend on this, so it won't get instantiated on its own.

我可以手动实例化它,显式地提供kernel.Get的依赖关系,但是感觉我不必这样做.

I could instantiate it manually, explicitly providing its dependencies with kernel.Get but it feels like I shouldn't have to do that.

即使没有其他依赖条件,我也可以在单例范围内紧急地使Ninject实例化类吗?

Can I make Ninject instantiate classes in singleton scope eagerly even when nothing else depends on it?

推荐答案

如果您不要求自己实例化某些东西,则不能ninject实例化某些东西. 简单的方法是要求ninject在组合根目录上实例化事物:

You cannot have ninject instantiate stuff in case you don't ask it to instantiate something yourself. The simple way is to ask ninject to instantiate things at composition root:

var kernel = new StandardKernel();
kernel.Bind<IFoo>().To<Foo>();
kernel.Load(AppDomain.CurrentDomain.GetAssemblies()); // loads all modules in assemlby
//...
// resolution root completely configured

kernel.Resolve<IFooSingleton>();
kernel.Resolve<IBarSIngleton>();

实际上有一个替代方法,它并不相同,但是可以用来实现类似的效果.它要求至少有一个立即实例化的其他服务: Ninject.Extensions.DependencyCreation . 它是这样的:

There is one alternative, actually, which is not the same, but can be used to achieve a similar effect. It requires that there is at least one single other service instantiated soon enough: Ninject.Extensions.DependencyCreation. It works like this:

kernel.Bind<string>().ToConstant("hello");

kernel.Bind<ISingletonDependency>().To<SingletonDependency>()
    .InSingletonScope();
kernel.DefineDependency<string, ISingletonDependency>();

kernel.Get<string>();
// when asking for a string for the first time
// ISingletonDependency will be instantiated.
// of course you can use any other type instead of string

为什么

Ninject与某些其他容器(例如Autofac)不同,它们不是分阶段构建"的.首先没有创建绑定,然后创建内核以使用它们的概念.以下是完全合法的:

Why

Ninject is unlike some other containers (for example Autofac) not "built" in stages. There's no concept of first creating the bindings, and then creating the kernel to use them. The following is perfectly legal:

kernel.Bind<IFoo>()...
kernel.Get<IFoo>()...
kernel.Bind<IBar>()...
kernel.Get<IBar>()...

因此ninject可能不知道何时您要实例化单例.有了autofac,它变得简单明了:

so ninject can't possibly know when you want the singletons to be instantiated. With autofac it's clear and easy:

var containerBuilder = new ContainerBuilder();

containerBuilder
    .RegisterType<Foo>()
    .AutoActivate();

var container = containerBuilder.Build(); // now

这篇关于我可以使用Ninject实例化不依赖任何内容的单例服务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆