Search code examples
c#.netinversion-of-controlautofacfactory-pattern

Factory and IOC together - how to use then both?


So I have this application where Im using IOC (autofac). In the mean time I found myself in position where I need a factory. Inside the factory I create new objects that has dependencies - so now I'm wondering, how could I marry these?

public class SubscriptionHandlerFactory : ISubscriptionHandlerFactory
{
    public ISubscriptionHandler GetProvider(StreamType streamType)
    {
        switch (streamType)
        {
            case StreamType.Rss:
                return new RssSubscriptionHandler(null,null,null,null);
            case StreamType.Person:
                return new PersonSubscriptionHandler(null, null, null, null);
            default:
                throw new ArgumentOutOfRangeException(nameof(streamType), streamType, null);
        }
    }
}

Solution

  • You could use named and keyed service and retrieve instances using IIndex<TKey, TService>

    Registration could look like this :

    builder.RegisterType<RssHandler>().Keyed<ISubscriptionHandler>(StreamType.Rss);
    builder.RegisterType<PersonHandler>().Keyed<ISubscriptionHandler>(StreamType.Person);
    builder.RegisterType<SubscriptionHandlerFactory>().As<ISubscriptionHandlerFactory>();
    

    and factory like this :

    public class SubscriptionHandlerFactory : ISubscriptionHandlerFactory
    {
        public SubscriptionHandlerFactory(IIndex<StreamType, ISubscriptionHandler> handlers)
        {
            this._handlers = handlers;
        }
    
        private readonly IIndex<StreamType, ISubscriptionHandler> _handlers;
    
        public ISubscriptionHandler GetProvider(StreamType streamType)
        {
            return this._handlers[streamType];
        }
    }