Click here to Skip to main content
15,881,812 members
Articles / Operating Systems / Windows

Inversion of Control (IoC) in XAML

Rate me:
Please Sign up or sign in to vote.
4.78/5 (17 votes)
16 Jan 2007CPOL9 min read 63.8K   533   36  
An article about Inversion of Control in XAML
using System;
using System.Windows;
using System.Windows.Markup;

namespace XamlIoc
{
	/// <summary>Markup Extension generating objects using <see cref="ObjectFactory"/>.</summary>
	[ContentProperty("Key")]
	public class ObjectFactoryExtension : MarkupExtension
	{
		private string key;

		/// <summary>Default constructor.</summary>
		public ObjectFactoryExtension()
		{
		}

		/// <summary>Constructor using a key.</summary>
		public ObjectFactoryExtension(string key)
		{
			this.key = key;
		}

		/// <summary>Object key to pass to <see cref="ObjectFactory"/>.</summary>
		[ConstructorArgument("key")]
		public string Key
		{
			get { return key; }
			set { key = value; }
		}

		/// <summary>Returns an instance from <see cref="ObjectFactory"/>.</summary>
		/// <param name="serviceProvider"></param>
		/// <returns></returns>
		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			if (Key == null)
			{
				throw new ArgumentNullException("Key");
			}

			return ObjectFactory.GetObject(Key);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect CGI
Canada Canada
Vincent-Philippe is a Senior Solution Architect working in Montreal (Quebec, Canada).

His main interests are Windows Azure, .NET Enterprise suite (e.g. SharePoint 2013, Biztalk Server 2010) & the new .NET 4.5 platforms.

Comments and Discussions