NEW to IInject
Assembly scanning.
var container = new Container();
ScanRules.Current.Clear();
ScanRules.Current.Add(ScanningRule.Inherits<System.Web.Mvc.Controller>());
container.Scan(a => a.Scan("SomeAssembly.dll"));
var container = new Container();
container.Scan(a =>
{
	a.Add(ScanningRule.InterfaceNamingDefault());
	a.Add(ScanningRule.PublicClass());
	a.ScanCallingAssembly();
});

First off, here are some POCOs for testing.
public class Dependent
{
	public Dependent() {}
	public Dependent(int id)
	{
		Id = id;
	}

	public int Id { get; set; }
}
public interface IInjectedProperty
{
	Dependent Dependent { get; set; }
}
public class InjectedProperty : IInjectedProperty
{
	public InjectedProperty(Dependent dependent)
	{
		Dependent = dependent;
	}

	public Dependent Dependent { get; set; }
}
public interface IDependencyTest
{
	int Id { get; set; }
	string Name { get; set; }
	Dependent Child { get; set; }
	IInjectedProperty Property { get; set; }
}
public class DependencyTest : IDependencyTest
{
	public DependencyTest(Dependent dependent)
	{
		Child = dependent;
	}

	public DependencyTest(int id, string name)
	{
		Id = id;
		Name = name;
	}

	public int Id { get; set; }
	public string Name { get; set; }
	public Dependent Child { get; set; }
	public IInjectedProperty Property { get; set; }
}

Now register the objects in the DI container.
public class ContainerTests
{
        public void SelectPropertyForInjectionTest2()
	{
		// Create a new Container.
		var container = new Container();

		// Register the objects in the container.
		container.Set<Dependent>();
		container.Map<IInjectedProperty>(m => m.To<InjectedProperty>());
		container.Map<int>(a => a.Return(1000));
		container.Map(typeof(ParentDependent)).With("Key").Apply();
		container.Map<IDependencyTest>(m =>
		{
			// Map the interface to the concrete type.
			m.To<DependencyTest>();
			// Set these properties to be injected.
			m.Inject(t => t.Id);
			m.Inject(t => t.Property);
		});

		// Retrieve the objects from the container.
		var test = container.Get<IDependencyTest>();
		var parent = container.Get<ParentDependent>("Key");

		// Verify all the items were set correctly
		// and the properties were injected with the proper values.
		Assert.IsNotNull(test);
		Assert.AreEqual(test.Id, 1000);
		Assert.IsNotNull(test.Property);
		Assert.IsNotNull(test.Property.Dependent);
		Assert.AreEqual(test.Property.Dependent.Id, 1000);
		Assert.IsNotNull(parent);
		Assert.AreNotEqual(parent.Dependency, test);
	}
}

Also, there is a way to inject dependencies into an object that does not exist in the container.
var container = new Container();
container.Map<int>().Return(10).Apply();
container.Map<string>().Return("Test").Apply();
var test = ObjectBuilder.Inject<DependencyTest>();
Assert.IsNotNull(test);
Assert.AreEqual(test.Id, 10);
Assert.AreEqual(test.Name, "Test");

Last edited Dec 20, 2012 at 7:34 AM by sbaker, version 5

Comments

No comments yet.