使用 ninject 创建初始化后对象
我是 Ninject(以及一般的 DI)新手。
我了解内核如何加载模块,并且到目前为止我编写的代码往往只有一行:
myKernel.Get<MyApp>()
它从模块中的绑定构造了我需要的所有内容。如果初始化后需要新实例,这些将由我为初始化绑定的工厂处理。到目前为止,工厂已经摆脱了任何 ninject 依赖关系,只需按需更新对象即可。
现在我已经达到了这样的程度,我需要考虑初始化后的对象创建,而我自己的工厂模式不再削减它。这将支持(远程)客户端的发布/订阅接口。对于与服务器的每个新连接,我希望根据 ninject 模块中定义的一组绑定创建新的 IClient
实例。这是否意味着我在初始化时传入的工厂必须有自己的内核(或对主内核的引用)? CommonServiceLocator 的功能在哪里?中超联赛有必要吗?
在我陷入死胡同之前,我认为最好在这里询问其他人如何解决这个问题。
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>()
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建工厂接口
对于 Ninject 2.3,请参阅 https://github.com/ninject/ninject.extensions.factory 并通过添加以下配置让它由 Ninject 实现。
对于2.2,请自行实现。此实现是容器配置的一部分,而不是您的实现的一部分。
Create a factory interface
For Ninject 2.3 see https://github.com/ninject/ninject.extensions.factory and let it be implemented by Ninject by adding the following configuration.
For 2.2 do the implementation yourself. This implementation is part of the container configuration and not part of your implementations.
看起来以下工厂模式可能会满足我的要求:
其中我有以下形式的构造函数:
It looks like the following pattern for factory might satisfy my requirements:
where I have constructor of the form: