i need run code register type factory pattern. in java static initialization block or in c++ static constructor.
how do in c#? static constructor gets run lazily , since type never referred in code, never gets registered.
edit: tried test see registration code work. doesn't seem working though.
using system; using system.collections.generic; using system.linq; using system.text; [assembly: assemblytest.registertofactory("hello, world!")] namespace assemblytest { [attributeusage(attributetargets.assembly, inherited = false, allowmultiple = true)] sealed class registertofactoryattribute : attribute { public registertofactoryattribute(string name) { console.writeline("registered {0}", name); } } class program { static void main(string[] args) { } } }
nothing gets printed.
how in constructor assembly level attribute
?
example:
[attributeusage(attributetargets.assembly, inherited = false, allowmultiple = true)] sealed class registertofactoryattribute : attribute { public type typetoregister { get; set; } public registertofactoryattribute(type typetoregister) { typetoregister = typetoregister; // registration code } }
usage:
[assembly:registertofactory(typeof(myclass))]
--edit on assembly level attributes--
after doing research, figured load assembly attributes if queried:
example:
object[] attributes = assembly.getexecutingassembly().getcustomattributes( typeof(registertofactoryattribute), false);
or
object[] attributes = assembly.getexecutingassembly().getcustomattributes(false);
don't know why putting code @ program load should it.
--edit--
i forgot:
have considered using mef
?? it's great solution problem.
example:
class myfactory { [importmany("myfactoryexport")] public list<object> registrations { get; set; } public myfactory() { assemblycatalog catalog = new assemblycatalog(system.reflection.assembly.getexecutingassembly()); compositioncontainer container = new compositioncontainer(catalog); container.composeparts(this); } } [export("myfactoryexport")] class myclass1 { } [export("myfactoryexport")] class myclass2 { } [export("myfactoryexport")] class myclass3 { }
Comments
Post a Comment