Ninject:共享的DI/IoC容器 [英] Ninject: Shared DI/IoC container

查看:103
本文介绍了Ninject:共享的DI/IoC容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在应用程序的各个层之间共享容器.我开始创建一个静态类,该类初始化容器并在容器中注册类型.

I want to share the container across various layers in my application. I started creating a static class which initialises the container and register types in the container.

public class GeneralDIModule : NinjectModule
{
    public override void Load()
    {
        Bind<IDataBroker>().To<DataBroker>().InSingletonScope();
    }
}

public abstract class IoC
{
    private static IKernel _container;

    public static void Initialize()
    {
        _container = new StandardKernel(new GeneralDIModule(), new ViewModelDIModule());
    }

    public static T Get<T>()
    {
        return _container.Get<T>();
    }
}

我注意到也有一种Resolve方法. Resolve和Get有什么区别?

I noticed there is a Resolve method as well. What is the difference between Resolve and Get?

在单元测试中,我并不总是希望容器中所有已注册的类型.有没有一种方法可以初始化一个空容器,然后注册我需要的类型.在单元测试中,我也会模拟类型,所以我也必须注册它们.

In my unit tests I don’t always want every registered type in my container. Is there a way of initializing an empty container and then register types I need. I’ll be mocking types as well in unit test so I’ll have to register them as well.

有一个Inject方法,但是它说实例的生命周期没有管理?

There is an Inject method, but it says lifecycle of instance is not managed?

有人可以用正确的方式设置我吗?

Could someone please set me in right way?

如何注册,注销对象和重置容器.

How can I register, unregister objects and reset the container.

推荐答案

默认情况下,Ninject绑定瞬态生活方式中的组件,并且Ninject不跟踪瞬态实例. Resolve在内部使用,除非您真正知道自己在做什么,否则不应在代码中使用Resolve.如果要模拟容器,请在github上使用ninject.moq扩展名.您所指的注入方法是针对您自己创建的实例.使用Get和TryGet方法.

Ninject by default binds components in a transient lifestyle and Ninject does not track transient instances. The Resolve is used internally and shouldn't be used by your code unless you really know what you are doing. If you want to mock your container, use the ninject.moq extension on github. The inject method you are referring to is for instances that you have created yourself. Use the Get and TryGet methods.

这篇关于Ninject:共享的DI/IoC容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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