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

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

问题描述

我(和一般DI)是新来Ninject。

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

我明白是怎么内核加载模块和code,我迄今书面往往有一行:

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依赖,只需newing了对象上的需求。

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.

现在我已经达到了一个点,我需要初始化后考虑对象创建和我自己的工厂模式不削减它了。这将是支持(远程)客户端的pub / sub接口。随着我的服务器每一个新的连接,我想按照一组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天全站免登陆