MEF 团队承诺 MEF 将支持 .Net 4.0 中的 DLR 插件。它是否已经发生并且我可以[导入]一些 IronPython 对象?

如果是,任何指向该主题的链接都会有所帮助。

有帮助吗?

解决方案

默认编程模型不支持 DLR,但可以编写其他支持它的编程模型,并且可以与默认编程模型一起使用。

其他提示

我知道这是旧的,但你可以看看 http://github.com/JogoShugh/IronPythonMef或查找NuGet包。

我拉出一些代码出一个称为ILoveLucene由布鲁诺Lopes的项目,并把它变成该独立回购和包。它才刚刚开始,但有一些包括一个例子,单元测试。

下面是一个例子:

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Reflection;
using IronPython.Hosting;
using IronPythonMef;

public interface IMessenger
{
    string GetMessage();
}

public interface IConfig
{
    string Intro { get; }
}

/// <summary>
/// Gets exported from IronPython into the CLR Demo instance.
/// </summary>
public static class PythonScript
{
    public static readonly string Code =
@"
@export(IMessenger)
class PythonMessenger(IMessenger):
    def GetMessage(self):
        return self.config.Intro + ' from IronPython'

    @import_one(IConfig)
    def import_config(self, config):
        self.config = config
";
}

/// <summary>
/// Also gets exported into the Demo instance.
/// </summary>
[Export(typeof(IMessenger))]
public class ClrMessenger : IMessenger
{
    [Import(typeof(IConfig))]
    public IConfig Config { get; set; }

    public string GetMessage()
    {
        return Config.Intro + " from C#!";
    }
}

/// <summary>
/// This will get imported into both the IronPython class and ClrMessenger.
/// </summary>
[Export(typeof(IConfig))]
public class Config : IConfig
{
    public string Intro
    {
        get { return "Hello"; }
    }
}

public class Demo
{
    [ImportMany(typeof(IMessenger))]
    public IEnumerable<IMessenger> Messengers { get; set; }

    public Demo()
    {
        // Create IronPython
        var engine = Python.CreateEngine();
        var script = engine.CreateScriptSourceFromString(PythonScript.Code);

        // Configure the engine with types
        var typesYouWantPythonToHaveAccessTo = new[] { typeof(IMessenger), typeof(IConfig) };
        var typeExtractor = new ExtractTypesFromScript(engine);
        var exports = typeExtractor.GetPartsFromScript(script,
            typesYouWantPythonToHaveAccessTo);

        // Compose with MEF
        var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        var container = new CompositionContainer(catalog);
        var batch = new CompositionBatch(exports, new ComposablePart[] { });
        container.Compose(batch);
        container.SatisfyImportsOnce(this);
    }

    public static void Main(string[] args)
    {
        var demo = new Demo();

        foreach (var messenger in demo.Messengers)
        {
            Console.WriteLine(messenger.GetMessage());
        }

        Console.Read();
    }
}

的输出是简单的:

Hello from IronPython!
Hello from C#!
scroll top