Home / Using the Container Outside of ObjectFactory

Using the Container Outside of ObjectFactory

New in version 2.5 is the ability to create an instance of the underlying Container class independent of the static ObjectFactory class (actually, you always could do this, but it’s much easier in 2.5).  The IContainer interface has roughly the same methods as ObjectFactory (the only major difference is that ObjectFactory.GetNamedInstance<T>(name) is IContainer.GetInstance<T>(name) )  You can build a Container with a single Registry object:

var container = new Container(new BasicActionRegistry());

Or more commonly, you can build the Container in a manner very similar to the ObjectFactory.Initialize() method.  One of the constructors for Container takes in an Action<ConfigurationExpression> expression that can be used to configure the Container in one atomic action like this code below:

var container = new Container(x =>
x.Scan(scanner =>
x.IncludeConfigurationFromConfigFile = true;

The ConfigurationExpression class is a Registry, so you can use all of the Registry DSL in the Lambda expression passed into the Container constructor.  In addition to the Registry DSL, you also have these options:

bool IncludeConfigurationFromConfigFile { set; }
void AddRegistry<T>() where T : Registry, new();
void AddRegistry(Registry registry);
void AddConfigurationFromXmlFile(string fileName);
void AddConfigurationFromNode(XmlNode node);

These other options will allow you to add configuration from additional Registry classes, the StructureMap section in the App.config file, or other Xml files.

Lastly, you can create a Container directly with a no argument constructor, then use the Inject() methods or later use the Configure() method.

public void Add_an_assembly_on_the_fly_and_pick_up_plugins2()
var container = new Container();
registry =>
registry.Scan(x =>
x.AssemblyContainingType(typeof (IService<>));
x.AddAllTypesOf(typeof (IService<>));
IList<IService<string>> instances = container.GetAllInstances<IService<string>>();