Mapping to constant value.
This happens for example when you need to resolve an automapper IMapper instance, Example in Ninject would be
var config = new MapperConfiguration( cfg => {
cfg.AddProfile( new MyMapperConfiguration() );
} );
Bind<MapperConfiguration>().ToConstant( config ).InSingletonScope();
Bind<IMapper>().ToConstant( config.CreateMapper() );
Bind different implementation based on the injecting type
This happens when a set of common classes depends on a common interface but the concrete implementation should be different. Example
public interface ICardService {}
public class TypeACardService : ICardService, ITypeACardService {
public TypeACardService( ICardValidator validator ) {
}
}
public class TypeBCardService : ICardService, ITypeBCardService {
public TypeBCardService( ICardValidator validator ) {
}
}
In this case with Ninject we are able to inject a different concrete implementation based on the type we are injecting to. Example
Bind<ICardValidator>().To<TypeAValidator>().WhenInjectedInto( typeof( ITypeACardService ) )
Bind<ICardValidator>().To<TypeBValidator>().WhenInjectedInto( typeof( ITypeBCardService ) )
The Simple Injector equivalent to this is:
container.RegisterConditional<ICardValidator, TypeAValidator>(
c => c.Consumer.ImplementationType == typeof(TypeACardService));
container.RegisterConditional<ICardValidator, TypeBValidator>(
c => c.Consumer.ImplementationType == typeof(TypeBCardService));
If you make a simple helper method, you can even mimic the Ninject API a bit more:
// Helper method:
private static bool WhenInjectedInto<TImplementation>(PredicateContext c) =>
c => c.Consumer.ImplementationType == typeof(TImplementation);
// Registrations
c.RegisterConditional<ICardValidator, TypeAValidator>(WhenInjectedInto<TypeACardService>);
c.RegisterConditional<ICardValidator, TypeBValidator>(WhenInjectedInto<TypeBCardService>);
Do note that since Simple Injector v4 it is impossible to make the binding contextual based on the service type of the consumer; you will have use the implementation type for this and if you really make the registration based on the service type, you will have to 'query' the implementation type to see if it implements the given interface. Doing this directly on service types can leads to hard to track bugs, as explained here. Note though that this problem is universal and holds for all DI Containers, not only for Simple Injector.