IoC:现有的运行时对象,而不是容器初始化的组件先决条件 [英] IoC: Existing runtime objects rather than container-initialised prerequisites for components

查看:79
本文介绍了IoC:现有的运行时对象,而不是容器初始化的组件先决条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言,我使用温莎城堡作为我的IoC容器.

In my case I am using Castle Windsor as my IoC container.

我想声明一个组件,其中构造函数参数之一将在运行时设置为现有对象,而不是让IoC容器在创建组件时创建该对象.例如,我的应用程序主窗体的实例.

I would like to declare a component, where one of the constructor arguments will be set to an existing object at runtime, rather than having the IoC container create the object when it creates the component. For example, the instance of my application's main form.

我怀疑有两种方法:

  1. 第一次通过容器创建对象,然后使用任何必需的运行时值对其进行配置,以便稍后组件向Windsor索取该对象时,即可使用它.
  2. 创建一个IFormProvider和一个具体的FormProvider,其中该组件需要注入一个IFormProvider值,随后该组件要求输入表单实例(即formProvider.Form).
  1. Create the object via the container for the first time, then configure it with any necessary runtime values so that when the component later on asks Windsor for it, it is ready to use.
  2. Create an IFormProvider and concrete FormProvider, where the component requires an IFormProvider value to be injected, which it subsequently asks for the form instance (i.e. formProvider.Form).

对此有任何进展吗?

推荐答案

这与 Unity 及其Fluent界面;只需调用容器的RegisterInstance方法.在设置Unity容器(针对v1.1,但1.2应该相似).

This is trivial to do with Unity and its Fluent interface; just call the RegisterInstance method of the container. There's a nice discussion of this at Setting Up the Unity Container (for v1.1, but 1.2 should be similar).

我还没有使用过温莎城堡,但显然AddComponentInstance是等效的.请参见>您是否可以注册现有的类型的实例在温莎容器中.

I haven't used Castle Windsor, but apparently AddComponentInstance is the equivalent. See Can you register an existing instance of a type in the Windsor Container.

这篇关于IoC:现有的运行时对象,而不是容器初始化的组件先决条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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