你可以注册在温莎容器的类型的现有实例? [英] Can you register an existing instance of a type in the Windsor Container?

查看:155
本文介绍了你可以注册在温莎容器的类型的现有实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在温莎IOC容器是可以注册的,而不是具有容器创建它,我已经有了一个实例的类型,?

In the Windsor IOC container is it possible to register a type that I've already got an instance for, instead of having the container create it?

推荐答案

对于所用容器的核心属性AddComponentInstance方法。

There is a AddComponentInstance method on the Container's Kernel property.

从单元测试:

[Test]
	public void AddComponentInstance()
	{
		CustomerImpl customer = new CustomerImpl();

		kernel.AddComponentInstance("key", typeof(ICustomer), customer);
		Assert.IsTrue(kernel.HasComponent("key"));

		CustomerImpl customer2 = kernel["key"] as CustomerImpl;
		Assert.AreSame(customer, customer2);

		customer2 = kernel[typeof(ICustomer)] as CustomerImpl;
		Assert.AreSame(customer, customer2);
	}

	[Test]
	public void AddComponentInstance_ByService()
	{
		CustomerImpl customer = new CustomerImpl();

		kernel.AddComponentInstance <ICustomer>(customer);
		Assert.AreSame(kernel[typeof(ICustomer)],customer);
	}

	[Test]
	public void AddComponentInstance2()
	{
		CustomerImpl customer = new CustomerImpl();

		kernel.AddComponentInstance("key", customer);
		Assert.IsTrue(kernel.HasComponent("key"));

		CustomerImpl customer2 = kernel["key"] as CustomerImpl;
		Assert.AreSame(customer, customer2);

		customer2 = kernel[typeof(CustomerImpl)] as CustomerImpl;
		Assert.AreSame(customer, customer2);
	}

这篇关于你可以注册在温莎容器的类型的现有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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