I want to write a factory for creating various types of "xxNotification" classes. My concrete "xxNotification" has dependencies registered with AutoFac. I would like to get/resolve instance of "xxNotification" using Autofac. How to do that?
public interface INotification
{
void Notify(string Action, int OrderID);
}
public class MagentoOrderStateNotification : INotification
{
private readonly GenericRepository<Order> _orderRepository;
private readonly OMRestIntegrationService _oMRestIntegrationService;
public MagentoOrderStateNotification(GenericRepository<Order> orderRepository, OMRestIntegrationService oMRestIntegrationService)
{
_orderRepository = orderRepository;
_oMRestIntegrationService = oMRestIntegrationService;
}
public void Notify(string Action, int OrderID)
{
//implementation...
}
}
public class NotificationFactory
{
public INotification GetNotification(string NotificationName)
{
switch (NotificationName)
{
case "MagentoOrderStateNotification":
//resolve instance of MagentoOrderStateNotification
}
}
}
This looks like a good candidate for the Strategy Pattern.
Interfaces
INotification Implementations
Strategy
Usage
Note that an alternative approach could be to use some "OrderType" state based on the OrderID to lookup the service to use (not sure it actually makes sense to pass OrderID into the Notify() method). But however you slice it this is an application design problem, not a DI problem.
Autofac Registration
There are a few ways you can configure Autofac to register multiple implementations of the same interface for use in the
NotificationStrategy
constructor. Here are a couple of examples:Scan
When the implementations are registered this way, Autofac will implicitly inject all implementations into any
IEnumerable<INotification>
constructor parameter.Cherry Pick