Share via


Neat Samples: Extend your F# program with MEF

Jomo Fisher—The Managed Extensibility Framework is an interesting new technology in .NET 4.0. It lets you set up a plug in system for your application so that your program can acquire new functionality just by, for example, adding a .dll into a particular directory.

This is a simple example in F#. This code sets up MEF hosting and asks for all extensions in the c:\extensions folder.

Code Snippet

  1. // Host.fs
  2. // A MEF host that eats tasty treats
  3. open System.Reflection
  4. open System.IO
  5. open System.ComponentModel.Composition
  6. open System.ComponentModel.Composition.Hosting
  7.  
  8. // Expose an interface
  9. type ITastyTreat =
  10.     abstract Description : string
  11.  
  12. // Set up MEF
  13. let catalog = new AggregateCatalog()
  14. let directoryCatalog = new DirectoryCatalog(@"c:\Extensions","*.dll")
  15. let container = new CompositionContainer(catalog)
  16. catalog.Catalogs.Add(directoryCatalog)
  17.  
  18. // Jar that will contain tasty treats
  19. type TreatJar() =
  20.     [<ImportMany(typeof<ITastyTreat>)>]
  21.     let cookies : seq<ITastyTreat> = null
  22.  
  23.     member __.EatTreats() =
  24.         cookies |> Seq.iter(fun tt->printfn "Yum, it was a %s" tt.Description)
  25.  
  26. let jar = TreatJar()
  27. container.ComposeParts(jar)
  28. jar.EatTreats()

This is how you implement an extension. Just build this into a .dll and drop it in the c:\extensions directory.

Code Snippet

  1. namespace ChocolateCookie
  2. open Host
  3. open System.ComponentModel.Composition
  4.  
  5. [<Export(typeof<ITastyTreat>)>]
  6. type ChocolateCookie() =
  7.     interface ITastyTreat with
  8.         member __.Description = "a delicious chocolate cookie"

Now, if you run the host program you should see this:

Yum, it was a a delicious chocolate cookie
Press any key to continue . . .

This posting is provided "AS IS" with no warranties, and confers no rights.

Comments

  • Anonymous
    March 09, 2010
    Hi, this is a very interesting article. Is it possible to load F# script files (fsx) instead of dll files using the DirectoryCatalog? Best regards, Oldrich