使用 ninject 创建初始化后对象 [英] Post-initialization object creation with ninject

查看:26
本文介绍了使用 ninject 创建初始化后对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ninject 的新手(以及一般的 DI).

I'm new to Ninject (and DI in general).

我了解内核是如何加载模块的,并且到目前为止我编写的代码往往只有一行:

I understand how the kernel loads modules, and the code I've written thus far tends to have a single line:

myKernel.Get<MyApp>()

它从我的模块中的绑定中构建了我需要的一切.如果在初始化后需要新实例,这些由我为初始化绑定的工厂来处理.到目前为止,工厂已经摆脱了任何 ninject 依赖,只是按需更新对象.

which constructs everything I need from the bindings in my module. If there's a requirement for new instances post initialization, these are taken care of by factories that I bind for initialization. Up to now, the factories have been free of any ninject dependencies, simply newing up objects on demand.

现在我已经到了需要考虑初始化后创建对象的地步,我自己的工厂模式不再削减它.这将支持(远程)客户端的发布/订阅接口.对于到我的服务器的每个新连接,我想根据 ninject 模块中定义的一组绑定创建新的 IClient 实例.这是否意味着我在初始化时传入的工厂必须有自己的内核(或对主内核的引用)?CommonServiceLocator 的功能在哪里.CSL有必要吗?

Now I have reached a point that I need to think about object creation after initialization and my own factory pattern is not cutting it any more. This would be to support a pub/sub interface for (remote) clients. With every new connection to my server, I would like to create new IClient instances according to a set of bindings defined in a ninject module. Does this mean that the factory I pass in at initialization has to have its own kernel (or a ref to the main kernel)? Where would CommonServiceLocator feature in this. Is CSL necessary?

在我走到死胡同之前,我认为最好在这里询问其他人可能如何解决这个问题.

Before I travel too far down dead-ends, I thought it would be best to ask here about how others might approach this problem.

推荐答案

创建工厂接口

public interface IClientFactory
{
    IClient CreateClient();
}

对于 Ninject 2.3,请参阅 https://github.com/ninject/ninject.extensions.factory 并让 Ninject 通过添加以下配置来实现.

For Ninject 2.3 see https://github.com/ninject/ninject.extensions.factory and let it be implemented by Ninject by adding the following configuration.

Bind<IClientFactory>().ToFactory();

对于 2.2 自己执行.此实现是容器配置的一部分,而不是您的实现的一部分.

For 2.2 do the implementation yourself. This implementation is part of the container configuration and not part of your implementations.

public class ClientFactory: IClientFactory
{
    private IKernel kernel;
    public ClientFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public IClient CreateClient()
    {
        return this.kernel.Get<IClient>();
    }
}

这篇关于使用 ninject 创建初始化后对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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