Note that there are some explanatory texts on larger screens.

plurals
  1. POActivator.CreateInstance: Dynamic Instantiation of Classes
    text
    copied!<p>I am designing a loosely-coupled structure. I want to <strong>call classes from different assemblies/namespaces via a code which is represented by a String</strong>. My design is, each of client's business rules is on different assemblies and not dependent on each other (ONE client is to ONE DLL ratio) so that when I made an update on business rules of 1 client, it would not affect the others. My attention now is on using Factory Design and using <strong>Activator.CreateInstance()</strong> Method.</p> <p>This is the project setup (2+n DLL's)</p> <pre><code> namespace Foundation; // where the interfaces/abstract resides namespace Factory; // has dependency on Foundation assembly namespace Client1; // client1's DLL, no dependency namespace Client2; // client2's DLL, no dependency The UI // only referenced to the Foundation and Factory not the Clients </code></pre> <p>The actual code</p> <pre><code> namespace Foundation { public interface IBusinessRules { string GetBusinessRule(); } } namespace Client1 //DLL for client 1 { public class BusinessRules : Foundation.IBusinessRules { public string GetBusinessRule() { return "Client1 Business Rule"; } } } namespace Client2 //DLL for client 2 { public class BusinessRules : Foundation.IBusinessRules { public string GetBusinessRule() { return "Client2 Business Rule"; } } } namespace Factory { public static class Invoker&lt;T&gt; where T: Foundation.IBusinessRules { public static T FetchInstance(string clientCode) { return (T)Activator.CreateInstance(Type.GetType(clientCode)); } } } //sample implementation that generates unhandled Exception using Factory; using Foundation; static void Main(string[] args) { //the parameter is maintained in the database IBusinessRules objClient1 = Invoker&lt;IBusinessRules&gt;.FetchInstance("Client1"); //should call Client1.BusinessRules method Console.WriteLine(objClient.GetBusinessRule()); Console.Read(); objClient = Invoker&lt;IBusinessRules&gt;.FetchInstance("Client2"); //should call Client2.BusinessRules method Console.WriteLine(objClient.GetBusinessRule()); Console.Read(); } </code></pre> <p>Any idea why my sample doesn't work? And any suggestion to improve the design? Thanks in advance.</p> <p><strong>How about using</strong> </p> <blockquote> <p>Expression.Lambda</p> </blockquote> <p>anyone?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload