Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Daniel is right. I defined a relationships of Import and Export as properties in my mapping classes. I loaded them as ComposablePartCatalog to MEF's container so that MEF can magically fetches corresponding instances on fly. It is within the mapping classes that I have some codes to new instances. Therefore, I have to find a way to let MEF to call back to those mapping classes to dispose the created resources when MEF is out of a process.</p> <p>I like Daniel's suggestion to introduce a class for my Export part. Since all my DI mappings are defined in the way of properties (getter and setters), I created a base class like this:</p> <pre><code>public class ComponentExporterBase: IDisposable { private List&lt;IDisposable&gt; _list; public ComponentExporterBase() { _list = new List&lt;IDisposable&gt;(); } protect void Add(IDisposable obj) { _list.Add(obj); } protected virtual void Dispose(bool disposing) { if (disposing) { foreach(var obj in _list) { obj.Dispose(); } _list.Clear(); } } public void Dispose() { Dispose(true); } } </code></pre> <p>With this base class, my mapping classes will be able to let MEF to do the disposing job. For example, here is one example:</p> <pre><code>internal class MyDIMappingClass : ComponentExporterBase { [Import] private IDataReader _dataReader { get; set; } [Export] private IController { get { var reader = _dataReader; var instance = new MyMainController(reader); base.Add(instance); return instance; } ... } </code></pre> <p>All my mapping classes are defined in the similar way, and they are much cleaner. The basic principle is that instances or resources which are created within a class should be disposed within the class, but not injected instances. In this way, I don't need to clean up any injected instances by MEF any more, as in this example:</p> <pre><code>public class MyMainController : IController { private IDataReader _dataReader; // dataReader is injected through CTOR public MyMainControler(IDataReader dataReader) { _dataReader = dataReader; ... } ... public void Dispose() { // dispose only resources created in this class // _dataReader is not disposed here or within the class! ...} } </code></pre> <p>By the way, I like to use properties as my imports and exports since the attributes have nothing to do a class' business logic. In other many cases, some classes are from third parties and I don't have access to their source codes to mark them as export.</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