Nine.Injection is a portable lightweight constructor injection library for singleton objects.
- Portable: Runs on Windows, Windows Phone 8, Windows Store, iOS, Android, etc.
- Always Singleton: Objects registered and resolved by the container are always singletons.
- Constructor Injection: Dependencies are expressed and injected by constructors only.
You can get Nine.Injection using NuGet:
Install-Package Nine.Injection
Dependencies are maintained by the Container
var container = new Container();
To map concrete implementations for an interface:
container.Map<IFoo, Foo>().Map<IFoo, Foo2>();
To map an existing instance for an interface:
container.Map<IFoo>(new Foo()).Map<IFoo>(new Foo2());
To map all public types that implements a specific interface:
container.MapAll<IFoo>(Assembly.GetExecutingAssembly());
To get the concrete implementation of an interface:
container.Get<IFoo>(); // Returns the last registered IFoo instance
To get all implementations that implements an interface:
container.GetAll<IFoo>(); // Returns all instances that implements IFoo
Objects get from the container are always singletons:
container.Map<IFoo, Foo>().Map<IFoo2, Foo>();
Assert.Equals(container.Get<IFoo>(), container.Get<IFoo>());
Assert.Equals(container.Get<IFoo>(), container.Get<IFoo2>());
Nine.Injection uses constructors to find dependencies:
public class UserService : IService
{
public UserService(IStorage storage) { ... }
}
To instantiate UserService
, a IStorage
is resolved from the container and passed to the constructor of UserService
.
If there are multiple arguments specified in the constructor, the one with the most arguments is used:
public UserService(IStorage storage)
public UserService(IStorage storage, ILogger logger) // This one is used
To inject all implementations of a given interface:
public ServiceContainer(params IService[] services)
public ServiceContainer(IEnumerable<IService> services)
In case of circular dependency, Lazy<>
can be used to break the cyclic reference.
public UserService(Lazy<IStorage> storage)
See the test specs to learn more about the behavior of Nine.Injection.