Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Need for new method in mmFactory.
Message
General information
Forum:
ASP.NET
Category:
The Mere Mortals .NET Framework
Miscellaneous
Thread ID:
00900738
Message ID:
00901092
Views:
15
>We are in need of a function in mmFactory like the one below;
>
>public interface IMyInterface
>{ void AMethod(); }
>
>public IMyInterface CreateBizObject(string FullClassName)
>{
>...
>...
>}
>
>How can we implement it?
>
>usage will be as follows;
>
>IMyInterface biz = mmFactory.CreateBizObject("MyNamespace.MyBizClass");

If you REALLY want to create a business object from a string (rather than using the conventional strongly typed approach using "new", you need to use reflection. You would have to pass both the class name and assembly name to the method as follows:
public IMyInterface CreateBizObject(string assemblyName, string className)
{
	// Load the assembly to use.
	Assembly asm = Assembly.LoadFrom(assemblyName);

	// Get the Type of the specified class
	Type ObjectType = asm.GetType(className, true);

	// Creates an instance of the specified type
	return (IMyInterface)Activator.CreateInstance(ObjectType);

}
Obviously, the problem with this approach is that you won't catch errors until run time since the compiler can't do type checking on this code. For example, if you pass a "className" that does NOT implement IMyInterface, you will get an "invalid cast" exception at run time.

Regards,
Kevin McNeish
Eight-Time .NET MVP
VFP and iOS Author, Speaker & Trainer
Oak Leaf Enterprises, Inc.
Chief Architect, MM Framework
http://www.oakleafsd.com
Previous
Reply
Map
View

Click here to load this message in the networking platform