<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Blog of Zachary Snow &#187; service-continer</title>
	<atom:link href="http://zacharysnow.net/tag/service-continer/feed/" rel="self" type="application/rss+xml" />
	<link>http://zacharysnow.net</link>
	<description></description>
	<lastBuildDate>Tue, 20 Dec 2011 19:41:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Implementing basic Dependency Injection using a Service Container</title>
		<link>http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=implementing-basic-dependency-injection-using-services-container</link>
		<comments>http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/#comments</comments>
		<pubDate>Mon, 21 Jun 2010 19:09:14 +0000</pubDate>
		<dc:creator>Zachary</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dependency-injection]]></category>
		<category><![CDATA[design-patterns]]></category>
		<category><![CDATA[service-continer]]></category>

		<guid isPermaLink="false">http://zacharysnow.net/?p=321</guid>
		<description><![CDATA[By extending your Service Container class, a very basic version of dependency injection can be implemented. We&#8217;ll implement two forms of dependency injection: constructor and property injection. We&#8217;ll start by defining the Injectable attribute. [AttributeUsage(AttributeTargets.Constructor &#124; AttributeTargets.Property, AllowMultiple = false, &#8230; <a href="http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>By extending your Service Container class, a very basic version of dependency injection can be implemented. We&#8217;ll implement two forms of dependency injection: constructor and property injection. </p>
<p><span id="more-321"></span></p>
<p>We&#8217;ll start by defining the <strong>Injectable</strong> attribute. </p>
<pre name="code" class="c#">
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Property,
	AllowMultiple = false, Inherited = true)]
public class InjectableAttribute : Attribute
{
}
</pre>
<p>We&#8217;ll use this attribute to mark our constructors and properties for dependency injection. Next we&#8217;ll define an interface for our dependency injector:</p>
<pre name="code" class="c#">
public interface IDependencyInjector
{
	T Construct&lt;T&gt;();
	void Inject(object instance);
}
</pre>
<p>We&#8217;ll define our service container like so:</p>
<pre name="code" class="c#">
public class ServiceContainer : IDependencyInjector, IServiceProvider
{
	Dictionary&lt;Type, Object&gt; services;

	public ServiceContainer()
		: base()
	{
		this.services = new Dictionary&lt;Type, object&gt;();
	}

	public void AddService(Type type, Object provider)
	{
		if(null == type)
			throw new ArgumentNullException("type");

		if(null == provider)
			throw new ArgumentNullException("provider");

		if(this.services.ContainsKey(type))
			throw new InvalidOperationException("A provider is already registered the type " + type);

		var providerType = provider.GetType();

		if(!type.IsAssignableFrom(providerType))
			throw new InvalidOperationException(providerType + " is not an instance of " + type);

		this.services.Add(type, provider);
	}

	public object GetService(Type type)
	{
		if(null == type)
			throw new ArgumentNullException("type");

		if(this.services.ContainsKey(type))
			return this.services[type];

		return null;
	}

	public void RemoveService(Type type)
	{
		if(null == type)
			throw new ArgumentNullException("type");

		this.services.Remove(type);
	}

	protected object GetInjectableService(Type type)
	{
		if(type == typeof(IDependencyInjector) ||
		   type == typeof(IServiceProvider))
		{
			return this;
		}
		else
		{
			object service = this.GetService(type);

			if(service == null)
				throw new InvalidOperationException("Failed to find " + type + " depenedency.");

			return service;
		}
	}

	public T Construct&lt;T&gt;()
	{
		ConstructorInfo injectableConstructor = null;
		foreach(ConstructorInfo constructor in typeof(T).GetConstructors())
		{
			foreach(Attribute attribute in constructor.GetCustomAttributes(true))
			{
				if(attribute is InjectableAttribute)
				{
					injectableConstructor = constructor;
					break;
				}
			}

			if(injectableConstructor != null)
				break;
		}

		if(injectableConstructor == null)
			throw new InvalidOperationException("No injectable constructor found.");

		var parameters = injectableConstructor.GetParameters();
		var services = new object[parameters.Length];

		int i = 0;
		foreach(ParameterInfo parameter in parameters)
			services[i++] = GetInjectableService(parameter.ParameterType);

		return (T)injectableConstructor.Invoke(services);
	}

	public void Inject(object instance)
	{
		foreach(PropertyInfo property in instance.GetType().GetProperties())
		{
			foreach(Attribute attribute in property.GetCustomAttributes(true))
			{
				if(attribute is InjectableAttribute)
				{
					if(!property.CanWrite)
						throw new InvalidOperationException(property.Name + " is marked as Injectable but not writable.");

					property.SetValue(instance, GetInjectableService(property.PropertyType), null);
				}
			}
		}
	}
}
</pre>
<p>You can now construct new instances and inject dependencies on existing instances. Some usage examples:</p>
<pre name="code" class="c#">
public interface IFoo
{
	int Value { get; }
}

public class Foo : IFoo
{
	public int Value
	{
		get;
		set;
	}

	[Injectable]
	public Foo()
	{
	}

	public void DoIt()
	{
		Console.WriteLine(this.Value);
	}
}

public interface IBar
{
	string Value { get; }
}

public class Bar : IBar
{
	IFoo foo;

	public string Value
	{
		get;
		set;
	}

	[Injectable]
	public Bar(IFoo foo)
	{
		this.foo = foo;
	}

	public void DoIt()
	{
		Console.WriteLine(this.Value + ": " + this.foo.Value);
	}
}

public class Baz
{
	[Injectable]
	public IFoo Foo
	{
		get;
		set;
	}

	[Injectable]
	public IBar Bar
	{
		get;
		set;
	}

	public void DoIt()
	{
		Console.WriteLine(this.Bar.Value + " | " + this.Foo.Value);
	}
}

class Program
{
	static void Main(string[] args)
	{
		var container = new ServiceContainer();

		var foo = container.Construct&lt;Foo&gt;();
		foo.Value = 5;
		container.AddService(typeof(IFoo), foo);

		var bar = container.Construct&lt;Bar&gt;();
		container.AddService(typeof(IBar), bar);
		bar.Value = "Hello World!";
		bar.DoIt();

		var baz = new Baz();
		container.Inject(baz);
		baz.DoIt();
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

