When trying to design a factory service in a project where i am using a dependency container i sometime find myself in this situation.
I have an interface, in this example ISettingsLoader
. ISettingsLoader
defines an interface for any class used to represent a page which displays a series of settings.
interface ISettingsLoader {
View LoadView();
}
Then i have several implementations: more often than not each implementation has its own dependencies. These are just examples: the dependencies of each implementation are usually very different.
class AudioSettingsLoader : ISettingsLoader
{
private IAudioSettingsService service;
public AudioSettingsLoader(IAudioSettingsService service){
this.service = service;
}
View LoadView(){
// loads the view
}
}
class NetworkSettingsLoader : ISettingsLoader
{
private INetworkInfoService service;
public NetworkSettingsLoader (INetworkInfoService service){
this.service = service;
}
View LoadView(){
// loads the view
}
}
The factory used to instantiate the various implementations is something like this:
class SettingsLoaderFactory
{
private IContainer container;
public SettingsLoaderFactory(IContainer container){
this.container = container;
}
IViewLoader GetViewLoader(string settingsType){
switch(settingsType)
{
case "AudioSettings":
return this.container.resolve(typeof(AudioSettingsLoader));
case "NetworkSettings":
return this.container.resolve(typeof(NetworkSettingsLoader));
//etc...
}
}
This type of approach works decently, but you have to inject the container, which is something to be worried about.
In this case, is it appropriate to inject a container?