.net - MEF 实例化和多线程

标签 .net c#-4.0 mef factory abstract-factory

我在 .Net 4.0 中使用 MEF 来节省大量抽象工厂代码和配置 gubbins。无法迁移到 .net 4.5,因为它尚未部署。

类(class)

/// <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 的实现,因此我们不能保证 它们是线程安全的——可重入的。但是,该类必须使用 Export 属性进行检测。

导出属性

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

    public Type ExpectedType { get; set; }
}
  • ExpectedType 只是注释什么的元数据 IMessageProcessor.ProcessMessage() 期望处理,纯粹是 实现细节。

我的问题是,我到处都读到每个导入实例都将是单例,无论其通过 Lazy<> 引用构造时的激活策略如何。

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

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

然后更改函数 GetMessageProcessor 以手动创建一个新实例,完全独立于 MEF。使用 MEF 共享实例 pulry 作为类型列表。

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;



    }

最佳答案

这样的事情应该有效:

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
      ...
   }
}

关于.net - MEF 实例化和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13473893/

相关文章:

c# - C#:加载漫游配置文件并以用户身份执行程序

.net - TSQL md5哈希与C#.NET md5不同

sql-server - 如何使用 Oracle 和 SQL Server 在 .NET 4.5 C# Entity Framework 6 中将列映射到大写?

C#:对象的 == 和 != 运算符的默认实现

c# - MEF无属性方法: lazy initialization by condition

c# - 字符串生成器有什么作用?

.net - 执行 .net 方法时如何重定向 Powershell 中的错误输出?

javascript - 根据 Iframe 的 src URL 的 Iframe 内容动态调整 Iframe 的大小

asp.net - 在 MVC 中使用 MEF 实现可插拔架构

.net - MEF:将类型与对象一起注入(inject)?