Neat Samples: MEF in F# Scripts
Jomo Fisher—I posted yesterday about using MEF in F# programs. In the comments Oldrich asked if it was possible to do the same thing in F# scripts. It is indeed possible. It actually looks like a really powerful combination because you can naturally extend your scripts just by adding new #load directives at the top.
There are three pieces to this sample. You have to break your interfaces out into a separate .fsx. Realistically, you’d probably do this in a real compiled F# program too so this isn’t a huge burden on simplicity.
Code Snippet
// MefInterfaces.fsx
// Expose an interface
type ITastyTreat =
abstract Description : string
Code Snippet
// ChocolateCookie.fsx
#r "System.ComponentModel.Composition"
#load "MefInterfaces.fsx"
namespace ChocolateCookie
open MefInterfaces
open System.ComponentModel.Composition
[<Export(typeof<ITastyTreat>)>]
type ChocolateCookie() =
interface ITastyTreat with
member __.Description = "a delicious chocolate cookie"
Code Snippet
// MefHost.fsx
#load "ChocolateCookie.fsx"
open System.Reflection
open System.IO
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
open MefInterfaces
// Set up MEF
let catalog = new AggregateCatalog()
let assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly())
let container = new CompositionContainer(catalog)
catalog.Catalogs.Add(assemblyCatalog)
// 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()
Thanks Oldrich, for giving me an excuse to try this out.
This posting is provided "AS IS" with no warranties, and confers no rights.
Comments
- Anonymous
March 11, 2010
Very interesting post! I wasn't that interested in MEF (except for extending Visual Studio) but that is a thought-provoking sample.