F#和MEF:导出函数 [英] F# and MEF: Exporting Functions
问题描述
因此,我试图在F#控制台应用程序中进行以下简单测试:
So, I was trying to get this simple test working in an F# console app:
open System.Reflection
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
[<Export(typeof<int -> string>)>]
let toString(i: int) = i.ToString()
[<EntryPoint>]
let main argv =
use catalog = new AssemblyCatalog(Assembly.GetEntryAssembly())
use container = new CompositionContainer(catalog)
let myFunction = container.GetExportedValue<int -> string>()
let result = myFunction(5)
0
我希望MEF能够正确解析该功能,但事实并非如此. 相反,我得到了:
I expected MEF to get the function properly resolved, but it doesn't. Instead, I get this:
类型的未处理异常
'System.ComponentModel.Composition.CompositionContractMismatchException'
发生在System.ComponentModel.Composition.dll
An unhandled exception of type
'System.ComponentModel.Composition.CompositionContractMismatchException'
occurred in System.ComponentModel.Composition.dll
其他信息:
Cannot cast the underlying exported value of type 'Program.toString (ContractName="Microsoft.FSharp.Core.FSharpFunc(System.Int32,System.String)")' to type 'Microsoft.FSharp.Core.FSharpFunc``2[System.Int32,System.String]'.
- 我在这里想念什么?
-
FSharpFunc(System.Int32, System.String)
和FSharpFunc``2[System.Int32, System.String]
有什么区别? - 通过MEF导入/导出F#函数的正确方法是什么?
- What am I missing here?
- What is the difference between
FSharpFunc(System.Int32, System.String)
andFSharpFunc``2[System.Int32, System.String]
? - What is the correct way to import/export F# functions via MEF?
推荐答案
编译器将顶级F#函数转换为方法,因此您的示例将编译为:
The compiler turns top-level F# functions into methods, so your example will be compiled as:
[Export(FSharpFunc<int,string>)]
public string toString(int i) { return i.ToString(); }
这可能是导致错误的原因.您可以通过调用一些返回函数的操作来强制编译器生成FSharpFunc
类型的属性获取器-即使是简单的标识函数也可以:
This is probably causing the error. You can force the compiler to produce a property getter of FSharpFunc
type by calling some operation that returns a function - even a simple identity function will don:
let makeFunc f = f
[<Export(typeof<int -> string>)>]
let toString = makeFunc <| fun (i:int) ->
i.ToString()
我还没有测试过,但是我认为它可以工作.也就是说,在这种情况下,使用简单的单方法接口可能更安全.
I have not tested this, but I think it could work. That said, it is probably safer to go with a simple single-method interface in this case.
这篇关于F#和MEF:导出函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!