Search code examples
c#wpfsimple-injector

Inject Type based on string parameter


I would like to have the IoC create types based on parameters. I also need guidance on where to store this parameter info.

I need to make classes based on a string file type, more specific, based on extension.

I have a simple file info class for data:

class info
{
    public string FileName { get; set; }
}

and I need to return classes based on that 'FileName' extension so that I can render a viewer.

I'm using DataTemplates in WPF and assigning the type to the view works great. I just need to assign the type based on the FileName.

Right now I'm just using a static array of extension strings new[]{".pdf",".html",".jpg"}; to determine which type to return. This is totally not sustainable.

I'd like to have a datasource that looked like this that:

Extension     Type
============= =============
.pdf          Webviewer
.html         Webviewer
.doc          Docviewer
.docx         Docviewer
.txt          Textviewer

ect.


Solution

  • Depends on which DI container you use. For instance, Simple Injector provides for ways to resolve dependencies based on a key: https://simpleinjector.readthedocs.org/en/latest/howto.html#resolve-instances-by-key