Service factory
A service factory can be used to create a service that depends on parameters in the request.
To use a service factory the ServiceFactory property on the Service attribute is used. The service factory should implement the Litium.Runtime.DependencyInjection.IServiceFactory interface. If the factory pointed out does not implement the IServiceFactory interface a startup error will occur.
Example of service factory registration:
[Litium.Runtime.DependencyInjection.Service(
ServiceType = typeof(IOrderFactory),
Lifetime = Litium.Runtime.DependencyInjection.DependencyLifetime.Transient,
ServiceFactory = typeof(OrderFactoryFactory))]
public interface IOrderFactory { } // ignore that the interface not have any methods.
public class OrderFactoryB2B : IOrderFactory {}
public class OrderFactoryB2C : IOrderFactory {}
public class OrderFactoryFactory : IServiceFactory<IOrderFactory> {
private readonly ShoppingCart _cart;
public OrderFactoryFactory(ShoppingCart cart)
{
_cart = cart;
}
public IOrderFactory Create()
{
return _cart.IsB2B ? new OrderFactoryB2B() : new OrderFactoryB2C();
}
}
Example of usage of the service factory registration:
public class MyController : Controller
{
public MyController(IOrderFactory orderFactory)
{
// orderFactory is now fetched based on data from the request and selecting either the OrderFactory for B2B or B2C.
}
}