c# - Factory pattern with Managed Ext Framwork (MEF) -
c# - Factory pattern with Managed Ext Framwork (MEF) -
i trying implement mill pattern mef.
here solution
core project
iclass objectfactory static class(this problem is)
project a
[export(typeof(iclass))] [exportmetadata("type", "typea")] public classa : iclass {}
projectb
[export(typeof(iclass))] [exportmetadata("type", "typeb")] public classb : iclass {}
i facing problem when trying create object dynamically
and here mill class:
public static class objectfactory { private static readonly compositioncontainer _container; [importmany] public static ienumerable<lazy<iclass, imetadata>> objecttypes; static objectfactory() { aggregatecatalog catalog = new aggregatecatalog(); catalog.catalogs.add(new directorycatalog(environment.currentdirectory)); _container = new compositioncontainer(catalog); seek { objecttypes = _container.getexports<iclass, imetadata>(); } grab (compositionexception compositionexception) { console.writeline(compositionexception.tostring()); console.readline(); } } public static iclass createobject(obecttype objecttype) { iclass outprovider; type typetoload = objecttypes.where(x => x.metadata.type == objecttype.tostring()).firstordefault().gettype(); outprovider = (iclass)activator.createinstance(typetoload); homecoming outprovider; } }
if want new "nonshared" instance provided on every phone call createobject suggest refactoring.
private static readonly compositioncontainer _container; static objectfactory() { var directorycatalog = new directorycatalog(environment.currentdirectory) _container = new compositioncontainer(directorycatalog); } public static iclass createobject(obecttype objecttype) { var objecttypes objecttypes = new list<lazy<iclass, imetadata>>(); seek { objecttypes.addrange(_container.getexports<iclass, imetadata>()); } grab (compositionexception compositionexception) { console.writeline(compositionexception.tostring()); console.readline(); } homecoming objecttypes.firstordefault(x => x.metadata.type == objecttype.tostring()); }
you see mef resolve new instances (non shared ones is) every time composes types or you phone call getexports (and other overload of function). alternatively can export iclass factories instead, have collection of there providers.
p.s. [importmany] on objecttypes fellow member in illustration superfluous, since not composing type (i don't believe can since static), setting programmatically output of getexports
c# mef factory-pattern
Comments
Post a Comment