c# - how to make DLL acess a class/object in the exe applicaiton in which it is loaded -
i have c# exe application loads dll runtime, know how can dll access public static class of application ??
this problem can sloved third dll containing contracts , commonly used stuff. declare interface in contracts assembly , inject object implementing dynamically loaded classes.
you cannot use static class, cannot implement interfaces. if need static use singleton pattern.
// in contracts assembly // defines same functionality in static class. public interface iservicecontract { void someservicemethod(); } // classes dynamically loaded dll public interface iaddin { void testmethod(); }
// in dynamically loaded assembly public class addinclass : iaddin { private iservicecontract _service; public addinclass(iservicecontract service) { _service = service; } public void testmethod() { _service.someservicemethod(); } }
// in main assembly (exe) public class implementsservicecontract : iservicecontract { public void someservicemethod() { console.writeline("hello world!"); } }
usage
iservicecontract service = new implementsservicecontract(); assembly assembly = assembly.loadfile(@"c:\mydll.dll"); var type = assembly.gettype("addinclass"); iaddin addin = (iaddin)activator.createinstance(type, service); addin.testmethod();
Comments
Post a Comment