c# - MEF ExportFactory<T> - How to properly dispose in a long-running application? -
basically, there easy way dispose of imports created exportfactory<t>
? reason ask because exports contain reference still around, such eventaggregator. don't want run issue i'm creating hundreds of these , leaving them laying around when not necessary.
i noticed when create objects exportlifetimecontext<t>
carries dispose it. but, don't want pass exportlifetimecontext
viewmodels requesting copies of viewmodel, hence pass value. (return factory.single(v => v.metadata.name.equals(name)).createexport().value;
)
when call dispose
on exportlifetimecontext<t>
call dispose on nonshared
part involved in creation of t
. won't dispose of shared
components. safe behaviour, because if nonshared
parts instantiated purely satisfy imports t
, can safely disposed won't used other imports.
the other way think achieve it, customise dispose
method chain dispose call other member properties import with, e.g.:
[export(typeof(ifoo))] public class foo : ifoo, idisposable { [import] public ibar bar { get; set; } public void dispose() { var bardisposable = bar idisposable; if (bardisposable != null) bardisposable.dispose(); } }
but type has no visibility of whether imported instance of ibar
shared
or nonshared
run risk of disposing of shared components.
i think hanging onto instance of exportedlifetimecontext<t>
safe way of achieving want.
not sure if helps, feels unnecessary wrapping, possibly:
public class exportwrapper<t> : idisposable { private readonly exportlifetimecontext<t> context; public exportwrapper<t>(exportlifetimecontext<t> context) { this.context = context; } public t value { { return context.value; } } public void dispose() { context.dispose(); } public static implicit operator t(exportwrapper<t> wrapper) { return wrapper.value; } public static implicit operator exportwrapper<t>(exportlifetimecontext<t> context) { return new exportwrapper<t>(context); } }
which possibly:
[import(typeof(ibar))] public exportfactory<ibar> barfactory { get; set; } public void dosomethingwithbar() { using (exportwrapper<ibar> wrapper = barfactory.createexport()) { ibar value = wrapper; // ibar; // ibar , nonshared imports disposed of after call finishes. } }
feels bit dirty...
Comments
Post a Comment