2012-11-20 134 views
2

在.NET 4.0中使用MEF来节省我大量的抽象工厂代码和配置gubbins。由于未部署,因此无法移至.net 4.5。MEF实例和多线程

/// <summary> 
/// Factory relies upon the use of the .net 4.0 MEF framework 
/// All processors need to export themselves to make themselves visible to the 'Processors' import property auto MEF population 
/// This class is implemented as a singleton 
/// </summary> 
public class MessageProsessorFactory 
{ 
    private static readonly string pluginFilenameFilter = "Connectors.*.dll"; 
    private static CompositionContainer _container; 
    private static MessageProsessorFactory _instance; 
    private static object MessageProsessorFactoryLock = new object(); 

    /// <summary> 
    /// Initializes the <see cref="MessageProsessorFactory" /> class. 
    /// Loads all MEF imports 
    /// </summary> 
    /// <exception cref="System.NotSupportedException"></exception> 
    private MessageProsessorFactory() 
    { 
     lock (MessageProsessorFactoryLock) 
     { 
      if (_container == null) 
      { 
       RemoveDllSecurityZoneRestrictions(); 

       //Create a thread safe composition container 
       _container = new CompositionContainer(new DirectoryCatalog(".", pluginFilenameFilter), true, null); 

       _container.ComposeParts(this); 
      } 
     } 
    } 

    /// <summary> 
    /// A list of detected class instances that support IMessageProcessor 
    /// </summary> 
    [ImportMany(typeof(IMessageProcessor), RequiredCreationPolicy = CreationPolicy.NonShared)] 
    private List<Lazy<IMessageProcessor, IMessageProccessorExportMetadata>> Processors { get; set; } 

    /// <summary> 
    /// Gets the message factory. 
    /// </summary> 
    /// <param name="messageEnvelope">The message envelope.</param> 
    /// <returns><see cref="IMessageProcessor"/></returns> 
    /// <exception cref="System.NotSupportedException">The supplied target is not supported: + target</exception> 
    public static IMessageProcessor GetMessageProcessor(MessageEnvelope messageEnvelope) 
    { 
     if (_instance == null) 
      _instance = new MessageProsessorFactory(); 

     var p = _instance.Processors.FirstOrDefault(
        s => s.Metadata.ExpectedType.AssemblyQualifiedName == messageEnvelope.AssemblyQualifiedName); 

     if (p == null) 
      throw new NotSupportedException(
       "The supplied type is not supported: " + messageEnvelope.AssemblyQualifiedName); 

     return p.Value; 

    } 

    /// <summary> 
    /// Removes any zone flags otherwise MEF wont load files with 
    /// a URL zone flag set to anything other than 'MyComputer', we are trusting all pluggins here. 
    /// http://msdn.microsoft.com/en-us/library/ms537183(v=vs.85).aspx 
    /// </summary> 
    private static void RemoveDllSecurityZoneRestrictions() 
    { 
     string path = System.IO.Path.GetDirectoryName(
          System.Reflection.Assembly.GetExecutingAssembly().Location); 

     foreach (var filePath in Directory.EnumerateFiles(path, pluginFilenameFilter)) 
     { 
      var zone = Zone.CreateFromUrl(filePath); 

      if (zone.SecurityZone != SecurityZone.MyComputer) 
      { 
       var fileInfo = new FileInfo(filePath); 
       fileInfo.DeleteAlternateDataStream("Zone.Identifier"); 
      } 
     } 
    } 
} 

_container.ComposeParts(this);之后被调用时,处理器会填充找到的所有IMessageProcessor实现。大。

注意

  • GetMessageProcessor是由许多线程调用。
  • 我们无法控制开发人员如何构造IMessageProcessor的实现类 ,因此我们无法保证 是线程安全的 - 可重入。但是,该类必须使用“导出”属性进行检测。

出口属性

[MetadataAttribute] 
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] 
public class MessageProccessorExportAttribute : ExportAttribute 
{ 
    public MessageProccessorExportAttribute() 
     : base(typeof(IMessageProcessor)) 
    { 
    } 

    public Type ExpectedType { get; set; } 
} 
  • ExpectedType是什么笔记 IMessageProcessor.ProcessMessage()预计将处理,纯粹 实现细节只是元数据。

我的问题是,我到处读到每个导入的实例都是Singleton,而不管它的激活策略是通过Lazy <>引用构造的。

因此,我们不能允许从GetMessageProcessor返回MEF中的实例,因为多个线程将获得相同的实例,这是不可取的。唉唉! 我想知道下面的“解决方法”是否是最好的方法,或者我有MEF坚持概念错误。

我的解决方法是将看似毫无意义的RequiredCreationPolicy = CreationPolicy.NonShared属性设置更改为CreationPolicy.Shared

然后改变函数GetMessageProcessor手动创建一个新的实例,真正从MEF中分离出来。使用MEF共享实例prulry作为类型列表。

IMessageProcessor newInstance = (IMessageProcessor)Activator.CreateInstance(p.Value.GetType()); 

完整的方法;

public static IMessageProcessor GetMessageProcessor(MessageEnvelope messageEnvelope) 
    { 
     if (_instance == null) 
      _instance = new MessageProsessorFactory(); 

     var p = _instance.Processors.FirstOrDefault(
        s => s.Metadata.ExpectedType.AssemblyQualifiedName == messageEnvelope.AssemblyQualifiedName); 

     if (p == null) 
      throw new NotSupportedException(
       "The supplied type is not supported: " + messageEnvelope.AssemblyQualifiedName); 

     // we need to create a new instance from the singleton instance provided by MEF to assure we get a instance un-associated with the MEF container for 
     // currently as of .net 4.0 it wants to keep references on objects which may impact memory consumption. 
     // As we have no control over how a developer will organise there class that exposes an Export, 
     // this could lead to multithreading issues as an imported lazy instance is a singleton regardless 
     // of the RequiredCreationPolicy. 
     // MEF is still invaluable in avoided a tone of abstract factory code and its dynamic detection of all supporting 
     // Exports conforming to IMessageProcessor means there is no factory config for us to maintain. 

     IMessageProcessor newInstance = (IMessageProcessor)Activator.CreateInstance(p.Value.GetType()); 

     return newInstance; 



    } 
+0

不会这种方法失败,如果一个'IMessageProcessor'实例都有一个'ImportingConstructor'而不是默认的构造函数?此外,它不会满足新实例的任何导入。 –

回答

2

像这样的东西应该工作:

public class MessageProsessorFactory 
{ 
    private const string pluginFilenameFilter = "Connectors.*.dll"; 
    private static readonly Lazy<CompositionContainer> _container 
     = new Lazy<CompositionContainer>(CreateContainer, true); 

    private static CompositionContainer CreateContainer() 
    { 
     RemoveDllSecurityZoneRestrictions(); 
     var catalog = new DirectoryCatalog(".", pluginFilenameFilter); 
     return new CompositionContainer(catalog, true, null); 
    } 

    public static IMessageProcessor GetMessageProcessor(MessageEnvelope messageEnvelope) 
    { 
     var processors = _container.Value.GetExports<IMessageProcessor, IMessageProccessorExportMetadata>(); 
     var p = processors.FirstOrDefault(s => s.Metadata.ExpectedType.AssemblyQualifiedName == messageEnvelope.AssemblyQualifiedName); 
     if (p == null) throw new NotSupportedException("The supplied type is not supported: " + messageEnvelope.AssemblyQualifiedName); 
     return p.Value; 
    } 

    private static void RemoveDllSecurityZoneRestrictions() 
    { 
     // As before. 
     // PS: Nice to see someone found a use for my code! :) 
     // http://www.codeproject.com/Articles/2670/Accessing-alternative-data-streams-of-files-on-an 
     ... 
    } 
} 
+0

我更喜欢使用Lazy <>中的另一个构造函数实例化容器的所有静态方法。我认为陪审团仍然在什么容器上。价值。根据IMessageProcessor的新实例或MEF仍然维护的共享引用的方式,GetExport将返回,并且期望您通知它可以在完成时处理实例,从而导致潜在的资源泄漏,因为没有回来,它也只给了我们一个内部持有的同一个实例的引用,类似于一个单例。我读过.Net 4.5 - – Terry

+0

@Terry:只要你的出口有'[PartCreationPolicy(CreationPolicy.NonShared)]',这个方法就会为每次调用GetMessageProcessor返回一个导出类的新实例'。 –

+0

显然不是,我刚刚发现这里描述的同样的问题:http://stackoverflow.com/questions/3203614/mef-lazy-importmany-with-creationpolicy-nonshared我认为这仍然是一个问题,悲哀。我发现文档没有说明这一点。它目前仍然只是通过Activator.CreateInstance(part.getType)的方式实现这一目标,但显然MEF很快就会提供这个功能.. http://blogs.msdn.com/b/nblumhardt/archive/2009/08 /28/dynamic-part-instantiation-in-mef.aspx – Terry