If you used Dictionary<string, IApplicationPrinter> , this does not necessarily mean that you will need to have a separate instance for each string , some of them can use the same instance.
If you do not want to do this, you can store factories in a dictionary. A factory can be an object that implements an interface (something like IApplicationPrinterFactory ), or just a delegate that can create an object. In your case, it will be Dictionary<string, Func<IApplicationPrinter>> . Performing this method is completely safe. To add to the dictionary, you would do something like:
FileConverters = new Dictionary<string, Func<IApplicationPrinter>>(); Func<IApplicationPrinter> printerFactory = () => new WordPrinter(); foreach (string ext in WordPrinter.PrintableExtensions) FileConverters.Add(ext, printerFactory);
If you are sure you want Dictionary<string, Type> , there is no way to limit this so that all types implement IApplicationPrinter . What you can do is create your own dictionary that checks the type when adding. This does not make compile-time security, but makes it more secure.
class TypeDictionary : IDictionary<string, Type> { private readonly Type m_typeToLimit; readonly IDictionary<string, Type> m_dictionary = new Dictionary<string, Type>(); public TypeDictionary(Type typeToLimit) { m_typeToLimit = typeToLimit; } public void Add(string key, Type value) { if (!m_typeToLimit.IsAssignableFrom(value)) throw new InvalidOperationException(); m_dictionary.Add(key, value); } public int Count { get { return m_dictionary.Count; } } public void Clear() { m_dictionary.Clear(); }
svick source share