开发者

MEF Recomposition - Does it preserve existing instances?

开发者 https://www.devze.com 2023-01-05 18:10 出处:网络
Suppose I have a MEF composition like this: public class Composition { [ImportMany(AllowRecomposition = true)]

Suppose I have a MEF composition like this:

public class Composition
{
    [ImportMany(AllowRecomposition = true)]
    IEn开发者_如何学Cumerable<ILongRunningProcess> Processes { get; set; }

    public static void Main(string[] args)
    {
         var composition = new Composition();
         using (var catalog = new DirectoryCatalog("."))
         {
             using (var container = new CompositionContainer(catalog)
             {
                 container.SatisfyImportsOnce(composition);
                 //Fire off long running processes in response to stimuli
             }
         }
    }
}

According to the documentation I've seen, I "have to consider thread-safety when using Recomposition."[MSDN]

Obviously for the case where I removed a type, I need to make sure that my long-running process can be garbage-collected safely. But for types that existed before the recomposition and still exist after the recomposition, will I get new instances back for the contents of Processes whenever recomposition occurs, or is MEF able to preserve existing instances of imports when a catalog is recomposed?

Based on the above article's suggestion that for ICollection<T> MEF will use the Clear() and Add(T) methods, I'm not hopeful, but I'd like to know for certain before I go write the synchronization code.

EDIT I just realized I can't use this in a static method; I've updated the code accordingly :)


You will get the same instances back unless the types with the ILongRunningProcess exports on them have the part creation policy set to NonShared.

This isn't really a thread-safety issue though. You do want to make sure that when recomposition occurs, nothing is accessing the MEF container (which includes things like accessing the Value property of a Lazy provided by MEF). So if your long running process is running on a different thread and it has its own imports, you can have threading problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消