How to create an Entity factory from a string instead of using the Type

Posts   
 
    
cgerecke
User
Posts: 10
Joined: 07-Oct-2008
# Posted on: 19-Feb-2009 16:11:04   

Hi,

I am trying to get hold of an EntityFactory (let's say CustomerEntityFactory) using a string like "customer" instead of using the Type which the EntityFactoryFactory expects. The "EntityFactoryFactory" expects a System.Type or EntityType as an argument to create the EntityFactory. How can I get the EntityFactory from a string instead? Would it be possible for me to write an extension method to EntityFactoryFactory to enable that functionality?

Thank You, Vish

MTrinder
User
Posts: 1461
Joined: 08-Oct-2008
# Posted on: 19-Feb-2009 17:27:08   

Two options spring to mind...

1) You can either use a big switch statement which checks the value of the string you provide and creates the relevant factory for you - this is a prime candidate for creating from a template so that it stays up to date as you regenerate the code.

2) The other option is to use reflection - have a look at http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Matt

cgerecke
User
Posts: 10
Joined: 07-Oct-2008
# Posted on: 19-Feb-2009 23:29:32   

Hi MTrinder,

Too bad that EntityFactoryFactory is not a partial class. I think all generated classes should be partial class just in case. But I came up with the following instead of a big if loop...

public static class Helpers { public static IEntityFactory GetFactory( string typeOfEntity ) { EntityType result = (EntityType) Enum.Parse(typeof(EntityType), typeOfEntity); return EntityFactoryFactory.GetFactory( result ); } }

Thank You, Vish