views:

363

answers:

3

I have been looking for a way to register a factory class in autofac using XmlConfiguration but the documentation seems a bit slim.

What I want to accomplish is to do the following in my configuration instead:

builder.Register(c => MyFactory.GetMyObject()).As<IMyObject>();

Are there any good way of doing this?

A: 

Autofac was originally built to be configured, even autowired, from code.

Perhaps what you're looking for is something like Spring.NET or Castle. These two frameworks were originally built to be configured, even autowired, from XML.

Justice
A: 

Handling registration from code seem to have some advantages to using web.config since it seems easier to handle complex dependencies this way.

The only concern I had when following the examples i could find was that all the registration was done in Global.asax. This is quite easy to fix by breaking out the registration to a separate Assembly though.

Andreas R
+1  A: 

The way to do this is to encapsulate your registration into an Autofac Module, which can be registered from XML. (Modules are described here: http://code.google.com/p/autofac/wiki/StructuringWithModules)

Your module would look something like:

public class MyModule : Module
{
  protected override void Load(ContainerBuilder builder)
  {
    builder.Register(c => MyFactory.GetMyObject()).As<IMyObject>();
  }
}

And the XML to register it:

<module type="MyModule" />
Nicholas Blumhardt