.NET 4.0에서 MEF와 함께 DLR을 사용하는 방법은 무엇입니까?
-
21-08-2019 - |
문제
MEF 팀의 MEF가 .NET 4.0의 DLR 플러그인을 지원할 것이라는 약속이있었습니다. 이미 일어 났고 일부 Ironpython 객체를 [수입] 할 수 있습니까?
그렇다면 주제에 대한 링크가 도움이됩니다.
해결책
기본 프로그래밍 모델은 DLR을 지원하지 않지만이를 지원할 다른 프로그래밍 모델을 작성할 수 있으며 기본 프로그래밍 모델과 함께 사용할 수 있습니다.
- MEF 프리미티브에 대한 블로그 게시물 (프로그래밍 모델을 만드는 데 사용됩니다).
- 루비 프로그래밍 모델이 어떻게 작동하는지에 대한 아이디어가 포함 된 블로그 게시물
- Intellipad에 대한 사용자 정의 명령을 작성하는 방법 (Intellipad는 MEF와 Python 프로그래밍 모델을 사용합니다)
다른 팁
나는 이것이 늙었다는 것을 알고 있지만 당신은 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#!
제휴하지 않습니다 StackOverflow