如何在.NET 4.0中使用MEF与DLR?

3

MEF团队承诺在.Net 4.0中支持DLR插件。这个承诺是否已经兑现?我能否[Import]一些IronPython对象呢?

如果是的话,带有相关主题链接的信息将会很有帮助。

2个回答

5

0

我知道这是旧的文章了,但是你可以看一下http://github.com/JogoShugh/IronPythonMef或者搜索NuGet包。

我从Bruno Lopes的项目ILoveLucene中提取了一些代码,并将其转化为这个独立的仓库和包。这只是一个开始阶段,但是已经包含了一些例子和单元测试。

这里有一个例子:

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#!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接