Search code examples
c#dependency-injectionsimple-injector

How to refactor this factory method?


I have the following factory method which simply returns the proper IDatabase implementation. I'd like to refactor this over to my SimpleInjector container, but unsure how.

    public class DALFactory
    {
        public static IDatabase GetDAL()
        {
            string asm = "SQL"; /* Hardcoded choice of DAL */
            if (asm == "XML")
                return new XmlDatabase();
            if (asm == "SQL")
                return new SqlDatabase();
            return null;
        }
    }

I've tried understanding how I can register a collection, but how should I tell SimpleInjector which one to use when asking for an instance of IDatabase in my program? Open to any ideas. Just a theoretical program I'm trying to refactor for practice. Using DI (IoC) for the first time it's been such a pleasant, eye opening experience so far!

I've tried doing this, am I close?

Container.RegisterCollection<IDatabase>(new [] { typeof(SqlDatabase), typeof(XmlDatabase)});
Container.Register<IDatabase, XmlDatabase>(Lifestyle.Singleton);
Container.Register<IDatabase, SqlDatabase>(Lifestyle.Singleton);

Solution

  • In case the asm value is either hard-coded, or based on a value in the configuration file, you are basically saying that a running application only has one specific version of IDatabase.

    This means that you should register as such:

    string asm = "SQL"; /* Hardcoded choice of DAL */
    if (asm == "XML")
        container.Register<IDatabase, XmlDatabase>();
    if (asm == "SQL")
        container.Register<IDatabase, SqlDatabase>();