Search code examples
f#type-providerscsharpcodeprovider

Loading assembly dynamically from a Typeprovider


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).


Solution

  • 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)