简体   繁体   中英

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);

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM