Search code examples
servicestackabstract-factoryfunq

Does ServiceStack's default IoC have something similar to ninject's .ToFactory() Method?


Using ninject, I'm able to create an abstract factory using the following syntax from the application's composition root:

kernel.Bind<IBarFactory>().ToFactory();

Does ServiceStack's default IoC container similar functionality? I'd like to implement an abstract factory in one of my service classes in order to create repositories as needed.

One suggestion I've heard was to use:

HostContext.Container.Resolve<[InsertDependancyHere]>()

but I'd like to avoid creating access to the container outside of the composition root (the Apphost.cs file).


Solution

  • As far as i could tell, ServiceStack's Funq IoC implementation does not include this Abstract Factory implementation, like Ninject's Abstract Factory support (or Castle Windsor's Typed Factory Facility, which i used to use).

    You can still avoid Service Locator anti-pattern by creating a concrete Factory implementation and injecting that to your classes.

       public class BarFactory : IBarFactory
       {
           // constructor inject dependencies to the factory - no service locator
           public BarFactory() { ... }
    
           // create objects from factory
           public IBar GetBar() { ... }
       }
    

    Your other classes can inject IBarFactory and call it directly.

    Func is bare-bones by design, so will not have all the same features. ServiceStack added some features, but mostly having to do with autowiring registration.

    If you can't create a concrete implementation for your factories, this other SO answer may show you how to do it yourself.