Ninject:共享 DI/IoC 容器

发布于 2024-09-02 05:25:42 字数 765 浏览 5 评论 0原文

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

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 方法。解决和获取有什么区别?

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

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

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

如何注册、取消注册对象和重置容器。

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>();
    }
}

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画尸师 2024-09-09 05:25:42

默认情况下,Ninject 以瞬态生活方式绑定组件,并且 Ninject 不跟踪瞬态实例。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文