0
Votes in Release
(breakdown)
Generic Class Factory Snippet

Description

For years I’ve been using a design pattern I picked up back in my Java days to help me make legacy classes more testable with Mock objects. I’ve always had a few doubts about it, but it’s been useful so many times that I’ve never bothered to change it. I always keep a handy code snippet for it on my dev machines and I can knock them out in seconds. I don’t like it because I have to create a new class factory for every type that I want to control. This evening I decided it was about time that I brought it up to date with C# 3.0 and .NET 3.5.

Usage for creating the default type:

[Test]
public void TestGenericClassFactory2()
{
GenericClassFactory<IMyClass, MyClass>.Dispenser = (args) =>
(IMyClass)Activator.CreateInstance(typeof(MyClass2), args);
IMyClass ad = GenericClassFactory<IMyClass, MyClass>.CreateInstance(1, 2, 3);
Assert.IsNotNull(ad);
Assert.AreEqual(ad.MyMethod(), 6);
Assert.IsTrue(ad is MyClass2);
}

Usage for creating a special instance (such as a mock):
[Test]
public void TestGenericClassFactoryBinding()
{
MyClass2 tmp = new MyClass2(2,3,4);
GenericClassFactory<IMyClass, MyClass>.Dispenser = (args) => tmp;
IMyClass ad = GenericClassFactory<IMyClass, MyClass>.CreateInstance(1, 2, 3);
Assert.IsNotNull(ad);
Assert.AreEqual(ad.MyMethod(), 9);
Assert.IsTrue(ad is MyClass2);
}

Go to this blog post: http://aabs.wordpress.com/2007/11/21/a-generic-class-factory-for-c-30/ for more information.


Files

Source Code classfactory.snippet
source code, 1K, uploaded Jan 29 2008  - 387 downloads


Work Items

Proposed

= Proposed

Active

= Active

Fixed

= Fixed

Closed

= Closed

There are no work items associated with this release.



Updating...
Page view tracker