Friday, February 13, 2009

C# Generic Service Provider

I use IServiceProvider all the time. Often times the method calling the IServiceProvider.GetService(Type serviceType) interface already knows exactly what the serviceType is that it's looking for.

This gets really annoying:

IMyInterface myInterface = serviceProvider.GetService(typeof(IMyInterface)) as
IMyInterface;

Not only is it verbose to type, but error prone when you cast the object returned by GetService.

Using generics, this is much easier and provides compile-time type safety:

IMyInterface myInterface = serviceProvider.GetService<IMyInterface>();

Yeah, you could define serviceProvider as an instance of MyServiceProvider:

class
MyServiceProvider : System.ComponentModel.Design.ServiceContainer

{


public T GetService<T>()

{


return (T)this.GetService(typeof(T));

}

}

But that's annoying too because you have to implement MyServiceProvider and use it anywhere you are working with IServiceProvider.

It would be alot more useful if IServiceProvider already had that generic implementation. Fortuantely, C# has Extension Methods. To create the generic GetService implementation for all users of IServiceProvider in your project, extend it like this:

namespace System
{
public
static
class
GenericServiceProvider
{
[System.Diagnostics.DebuggerNonUserCode]
public
static T GetService<T>(this
IServiceProvider serviceProvider)
{
return (T)serviceProvider.GetService(typeof(T));
}
}
}

Enjoy


No comments:

Post a Comment