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
- // Host.fs
- // A MEF host that eats tasty treats
- open System.Reflection
- open System.IO
- open System.ComponentModel.Composition
- open System.ComponentModel.Composition.Hosting
- // Expose an interface
- type ITastyTreat =
- abstract Description : string
- // Set up MEF
- let catalog = new AggregateCatalog()
- let directoryCatalog = new DirectoryCatalog(@"c:\Extensions","*.dll")
- let container = new CompositionContainer(catalog)
- catalog.Catalogs.Add(directoryCatalog)
- // Jar that will contain tasty treats
- type TreatJar() =
- [<ImportMany(typeof<ITastyTreat>)>]
- let cookies : seq<ITastyTreat> = null
- member __.EatTreats() =
- cookies |> Seq.iter(fun tt->printfn "Yum, it was a %s" tt.Description)
- let jar = TreatJar()
- container.ComposeParts(jar)
- 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
- namespace ChocolateCookie
- open Host
- open System.ComponentModel.Composition
- [<Export(typeof<ITastyTreat>)>]
- type ChocolateCookie() =
- interface ITastyTreat with
- 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