concept iingredient in category dependency injection

appears as: IIngredient, n IIngredient
Dependency Injection

This is an excerpt from Manning's book Dependency Injection.

Whereas your application’s root types will typically be resolved by their concrete types, loose coupling requires you to map Abstractions to concrete types. Creating instances based on such maps is the core service offered by any DI Container, but you must still define the map. In this example, you map the IIngredient interface to the concrete SauceBéarnaise class, which allows you to successfully resolve IIngredient:

var builder = new ContainerBuilder();

builder.RegisterType<SauceBéarnaise>()
    .As<IIngredient>();    #1  

IContainer container = builder.Build();

ILifetimeScope scope = container.BeginLifetimeScope();

IIngredient sauce = scope.Resolve<IIngredient>();    #2  

#1   Maps a concrete type to an Abstraction
#2   Resolves the SauceBéarnaise class

The As<T> method allows a concrete type to be mapped to a particular Abstraction. Because of the previous As<IIngredient>() call, SauceBéarnaise can now be resolved as IIngredient.

Although Simple Injector’s ability to Auto-Wire concrete types certainly can come in handy from time to time, loose coupling requires you to map Abstractions to concrete types. Creating instances based on such maps is the core service offered by any DI Container, but you must still define the map. In this example, you map the IIngredient interface to the concrete SauceBéarnaise class, which allows you to successfully resolve IIngredient:

var container = new Container();

container.Register<IIngredient, SauceBéarnaise>();  #1  

IIngredient sauce =
    container.GetInstance<IIngredient>();    #2  

#1   Maps an Abstraction to a particular implementation
#2   Resolves SauceBéarnaise as an IIngredient

You use the Container instance to register types and define maps. Here, the generic Register method allows an Abstraction to be mapped to a particular implementation. This lets you register a concrete type. Because of the previous Register call, SauceBéarnaise can now be resolved as IIngredient.