Loading assembly dynamically from a Typeprovider

2019-09-12 06:22发布

I'm trying to add a feature to a type provider I'm working on to allow the user to specify a type. with Since type providers cannot provide generic methods, it seems the only way to do it is to reference the assembly that has the type.

I've tried to make a proof of concept for this using a type from the Owin library, but I'm running into an issue when trying to use the provided type:

enter image description here

It says it cannot find the file, even though it obviously exists, or else the CSharpCodeProvider that I'm using would give an error (which it has done before for incorrect file paths). I've tried reproducing this problem in a seperate non-type-providing project, but it works there.

The code for this project is here (input-type branch): https://github.com/isaksky/routeprovider/tree/input-type

You can see the problem by opening the main RouteProvider Solution, and debugging doing the DebugOwin sample (it will open a new instance of visual studio for a sample solution that uses the RouteProvider).

2条回答
可以哭但决不认输i
2楼-- · 2019-09-12 06:49

Dmitry's solution is one way to do it. The alternative is to simply make sure that your TP dependencies are located in the same folder that the TP itself resides in. We use this mechanism for the Azure Storage TP.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-09-12 06:57

Someone linked this answer, which has an explanation of the issue and a solution:

Type provider calling another dll in F#

I ended up having to use the typeprovider config (cfg)'s ReferencedAssemblies, like this:

      _assemblyResolver <- ResolveEventHandler(fun _ args ->
        let expectedName = (AssemblyName(args.Name)).Name + ".dll"
        let asmPath = 
            cfg.ReferencedAssemblies
            |> Seq.tryFind (fun asmPath -> IO.Path.GetFileName(asmPath) = expectedName)
        match asmPath with
        | Some f -> Assembly.LoadFrom f
        | None -> null)
      System.AppDomain.CurrentDomain.add_AssemblyResolve(_assemblyResolver)
查看更多
登录 后发表回答