3

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

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

4

2 回答 2

5

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

于 2009-07-02T18:08:34.810 回答
0

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

我从 Bruno Lopes 的一个名为 ILoveLucene 的项目中提取了一些代码,并将其变成了这个独立的 repo 和包。它才刚刚开始,但包含一些示例和单元测试。

这是一个例子:

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#!
于 2012-11-13T23:08:36.627 回答