BFG: DSL configuration syntax for Autofac IoC Container
I've added another Autofac extension module to the Photon.NET. It is inspired by Binsor and provides the ability to use custom DSL configuration syntax to set up Autofac container.
NB: BFG goes for "CFG with Boo" (although 9000 plays well, too)
Leveraging BFG configuration for Autofac yields following advantages:
- It does not have syntactic noise of XML configurations
- Types are resolved, so you do not have to manually type all the full names for components and services
- You can use lambda expressions for registrations, call methods or write anything that you could write in .NET language
- Custom syntactic shortcuts and helpers could be added
- Native .NET performance (after the initial start-up)
There is nothing really complex down there (and the actual implementation has also been quite simple). You just need to imagine that you are writing container setup script in Boo against the ContainerBuilder instance.
Let's go directly to the example. I'll be using Samples/Photon.BfgSample as a reference (see tag 0.0.42.0 for the version of codebase at the moment of writing this article)
That's how simple xml configuration might look like:
<modules>
<module type="Photon.LoggingModule, Photon.Stack" />
</modules>
<components>
<component type="Photon.BfgRunner.Tools.Dice, Photon.BfgRunner"
service="Photon.BfgRunner.Tools.IDice, Photon.BfgRunner" >
<parameters>
<parameter name="randSeed" value="10" />
</parameters>
</component>
<component type="Photon.BfgRunner.Tools.ResistantRagDoll, Photon.BfgRunner"
name="RagDoll"
scope="factory" />
<component type="Photon.BfgRunner.Tools.MagicPlasmaWand, Photon.BfgRunner"
name="MagicPlasmaWand" />
</components>
And this is the corresponding BFG script:
import Photon.BfgRunner.Tools
Load(LoggingModule())
Register(ResistantRagDoll, "RagDoll").FactoryScoped()
Register(MagicPlasmaWand, "MagicPlasmaWand")
Register(Dice(10),IDice)
Note that every Register statement works just like normal ContainerBuilder.Register and thus you have access to all the fluent API calls for adding additional services, naming, adding parameters, changing component ownership etc.
You can load this file into the container, using statement:
var container = ContainerUtil.LoadSyntax("Config.bfg")
where LoadSyntax is simply a helper routine to build container with ConfigurationModule from the passed Config.bfg.
public static IContainer LoadSyntax(string syntaxFile)
{
Enforce.ArgumentNotNullOrEmpty(syntaxFile, "syntaxFile");
var builder = new ContainerBuilder();
builder.RegisterModule(new ConfigurationModule(syntaxFile));
return builder.Build();
}
So what do you think so far?
Tuesday, September 23, 2008 at 1:29
Reader Comments