Home
Manage Your Code
Snippet: TypeAlias using TypeDelegator and IServiceProvider (C#)
Title: TypeAlias using TypeDelegator and IServiceProvider Language: C#
Description: A problems with the .NET implementation of IServiceProvider is that the locator service is keyed by Type, using this method a alias can be create. Views: 2444
Author: Schalk van Wyk Date Added: 10/12/2008
Copy Code  
1public sealed class TypeAlias : TypeDelegator
2{
3	private string _alias;
4	
5	public TypeAlias(Type type, string alias) : base(type)
6	{
7		this._alias = alias;
8	}
9	public override Type BaseType
10	{
11		get { return base.typeImpl; }
12	}
13	public override bool Equals(object obj)
14	{
15		TypeAlias that = obj as TypeAlias;
16		if (that != null)
17			return (that.typeImpl == this.typeImpl) && (that._alias == this._alias);
18		else
19			return base.Equals(obj);
20	}
21	public override int GetHashCode()
22	{
23		return base.GetHashCode() ^ this._alias.GetHashCode();
24	}
25}
Usage
class FooService
{}

FooService foo = new FooService();

IServiceContainer sc = new ServiceContainer();
sc.AddService(typeof(FooService), foo);

// how do we add a second FooService?

TypeAlias lonalias = new TypeAlias(typeof(FooService), "lon");
TypeAlias nycalias = new TypeAlias(typeof(FooService), "nyc");

FooService lonfoo = new FooService();
FooService nycfoo = new FooService();

sc.AddService(lonalias, lonfoo);
sc.AddService(nycalias, nycfoo);

bool b1 = (sc.GetService(lonalias) == lonfoo); // true
bool b2 = (sc.GetService(nycalias) == nycfoo); // true

bool b3 = typeof(FooService).IsAssignableFrom(lonalias); // true
bool b4 = lonalias.IsSubclassOf(typeof(FooService)); // true
Notes
IServiceProvider and IServiceContainer are a very interesting pattern that enable a kind of inheritance called environmental acquisition, sometimes also known as the service locator pattern. A problems with the .NET implementation of IServiceProvider is that the locator service is keyed by Type. Only one object of that type can ever retrieved from a service heirarchy. Indexing by type rseults in a well organised and compiler managed namespace, as well as queries returning objects of a known type. However, there may be times when it might be desireable to have multiple object of the same type in the service heirarchy. This solution uses the TypeDelegator class to create TypeAlias 'Types' behave as is they were derived from their delegated type and only compare equal to another TypeAlias with the same delgated type and alias name. TypeAlias instances can be used as keys in a service heirarchy, and allow more than one instance of the same type to exist.