寻找等效于StructureMap的ObjectFactory.GetInstance()方法的Ninject [英] Looking for Ninject equivalent of StructureMap's ObjectFactory.GetInstance() method

查看:123
本文介绍了寻找等效于StructureMap的ObjectFactory.GetInstance()方法的Ninject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC项目中使用Ninject,并且在Ninject.Mvc中使用了自动注册功能,并在我的应用程序类中设置了绑定.但是,我有一个地方要创建一个与这些绑定分开的实例.在StructureMap中,您可以执行var foo = ObjectFactory.GetInstance<IFoo>();,它将为您解决该问题. Ninject 2中有等效功能吗?我似乎在任何地方都找不到.

I'm using Ninject in an MVC project and I've used the autoregistration features in Ninject.Mvc and have my bindings set up in my application class. However, I have a place where I want to create an instance separate from those bindings. In StructureMap, you can do var foo = ObjectFactory.GetInstance<IFoo>(); and it will resolve it for you. Is there an equivalent in Ninject 2? I can't seem to find it anywhere.

推荐答案

AFAIK,NInject没有这样的静态方法,因此所有解析都应使用某个内核.

AFAIK, NInject doesn't have static method like this so all resolving should go to some kernel.

但是您可以轻松实现它;

But you can implement it easily;

 class ObjectFactory
 {
     static IKernel kernel = new StandardKernel(.....);
     public static T GetInstance<T>()
     {
          return kernel.Get<T>();
     }
 }

尽管,IMO,NInject作为DI容器比作为服务定位器有用得多.

Although, IMO, NInject is much more useful as DI container than as service locator.

这篇关于寻找等效于StructureMap的ObjectFactory.GetInstance()方法的Ninject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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