在可移植类库中使用F#JsonProvider失败

时间:2014-03-12 21:54:38

标签: f# type-providers f#-data

我试图使用JsonProvider,当我调用一个函数时,我收到以下错误:

System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in PortableLibrary1.dll
Additional information: The type initializer for '<StartupCode$PortableLibrary1>.$PortableLibrary1' threw an exception.

我有一个基本的控制台应用程序如下:

module Pinit =
   open FSharp.Data

   type JsonT = JsonProvider<"""..\myFile.json""">
   let doc = JsonT.Load("""..\nyFile.json""")
   let result = doc.GeneratedAt

[<EntryPoint>]
let main argv = 
    printfn "%A" Pinit.doc.GeneratedAt
    0 

在ConsoleApplication中运行时,它按预期工作。 如果我按如下方式创建F#可移植类库:

module Pinit =
   open FSharp.Data

   type JsonT = JsonProvider<"""..\myFile.json""">
   let doc = JsonT.Load("""..\nyFile.json""")
   let result = doc.GeneratedAt

创建另一个控制台应用程序并引用该可移植类库并按如下方式调用代码:

open PortableLibrary1

[<EntryPoint>]
let main argv = 
    printfn "%A" Pinit.result
    0 

当我运行程序时,它会生成上面定义的异常:

我怀疑它是因为FSharp.Core的版本,但是我想知道我是做错了什么还是有办法让它工作?

版本:

-- ConsoleApplication --
FSharp.Core = 4.3.1.0

-- PortableClassLibrary --
FSharp.Core = 3.3.1.0
FSharp.Data = NuGet Version: 2.0.0

1 个答案:

答案 0 :(得分:2)

让绑定编译成静态成员,而在.NET中,当静态初始化程序中有异常时,真正的异常会被伪装。

如果您通过更改为let result() = doc.GeneratedAtprintfn "%A" (Pinit.result())将其转换为函数调用,则会获得真正的异常:

Only web locations are supported

便携式配置文件不支持访问文件系统。因此,在PCL中,您可以拥有Web URL或从嵌入式资源手动加载。请参阅此处以获取示例:https://github.com/ovatsus/Apps/blob/master/Trains/Stations.fs#L65。或者,您可以在控制台项目中加载File.ReadAllText的文件,并将其传递给PCL。

这是一个Portable Profile(Legacy)项目,它是Profile 47(和FSharp.Core 2.3.6.0)。然后我还测试了一个Portable Profile项目,它是Profile 7(和FSharp.Core 3.3),并注意到它无法正常工作,而是给出了这个例外

Method not found: 'FSharp.Data.Runtime.JsonValueOptionAndPath FSharp.Data.Runtime.JsonRuntime.TryGetPropertyUnpackedWithPath(FSharp.Data.Runtime.IJsonDocument, System.String)'.

我创建了一个github问题来跟踪:https://github.com/fsharp/FSharp.Data/issues/521