Register Types with the Container

Prerequisite: Declare your Wireup Dependency

In order for the IoC container to create implementations of abstract types, including interfaces, the concrete types must first be registered.

Registering via Declaration

Apply the ContainerRegisterAttribute to an implementation type, indicating the base-type for which the implementation type will be substituted.

public interface IBeNamed
{
	string Name { get; }
}

[ContainerRegister(typeof(IBeNamed))]
public class A : IBeNamed
{
	public A() { this.Name = this.GetType().Name; }
	public string Name { get; protected set; }
}

Registrations made in this way will be performed on the Root container and should be considered global.

Direct Registration via the Fluent Interface

Each container maintains a registry. In most cases, it inherits the registrations of the ambient container at the time it is created. You may make new registrations against any container.

A fluent registration equivalent to the one above is:

Container.Root
	.ForType<IBeNamed>()
		.Register<A>()
		.End();

Result

Using either of the above registrations, the following test will resolve the IBeNamed interface as expected:

[TestMethod]
public void CreateNew_CanCreateRegisteredInterface()
{
	// Create the instance...
	var instance = Create.New<IBeNamed>();

	// Ensure it is what we think it is...
	Assert.IsInstanceOfType(instance, typeof(IBeNamed));
	Assert.IsInstanceOfType(instance, typeof(A));
	Assert.AreEqual("A", instance.Name);
}

Other Useful Registration Info

For specialized registrations see Singletons & Specialized Registrations.

~P

Last edited Sep 1, 2013 at 6:15 PM by cerebralkungfu, version 9

Comments

No comments yet.