Entity factory

A

Andrus

I need to create Factory() method which creates entity objects from
string type names ( e.q. "Customer", "Product" ) for 3.5 WinForms Linq
application.

I tried code below but got error shown in comment.

How to fix this code?
How to create constructor from string type name and call it
using reflection or any other solution ?

Andrus.


class TestApplication {

static void Main() {
object Customer = Factory("Customer");
object Product = Factory("Product");
}

static object Factory(string typeName) {
Type t = Type.GetType(typeName);
// error: type expected.
return new <t>();
}
}

class Customer { public string Name { get; set; } }

class Product { public string Code { get; set; } }
 
A

Arne Vajhøj

Andrus said:
I need to create Factory() method which creates entity objects from
string type names ( e.q. "Customer", "Product" ) for 3.5 WinForms Linq
application.

I tried code below but got error shown in comment.

How to fix this code?
How to create constructor from string type name and call it
using reflection or any other solution ?
static object Factory(string typeName) {
Type t = Type.GetType(typeName);
// error: type expected.
return new <t>();
}

Try:

Assembly.Load("YournAssembly").CreateInstance("YourClass")

or:

Assembly.GetExecutingAssembly().CreateInstance("YourClass")

Arne
 
M

Marc Gravell

Since you are using 3.5, and assuming your "Type t =
Type.GetType(typeName);" line works (i.e. t is non-null), then note
that I posted some factory Type extension code the other day that is
significantly quicker than reflection, and allows access to
parameterised ctors; it also makes it easy to work with different
interface/base-classes without fuss:

http://groups.google.co.uk/group/mi....csharp/browse_thread/thread/b5d5a729ace312ad

In this particular case, you might choose to find your types ahead of
time and throw the functions in a Dictionary<string,Func<object*>>, so
you can use object obj = factory["Customer"]();

Just a thought. Of course, simple CreateInstance() may do everything
you need...

*=replace object with some common base-class/interface if you like.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top