Skip to content

Instantly share code, notes, and snippets.

@michaeljbailey
Last active August 29, 2015 14:08
Show Gist options
  • Save michaeljbailey/78f748068cd0b34cec27 to your computer and use it in GitHub Desktop.
Save michaeljbailey/78f748068cd0b34cec27 to your computer and use it in GitHub Desktop.
public class CommandLineArgumentParserHandler : IHandler<string, IArgumentParser>
{
private readonly CommandLineArgumentParser _service;
public CommandLineArgumentParserHandler(CommandLineArgumentParser service)
{
_service = service;
}
public IArgumentParser GetService()
{
return _service;
}
public bool CanHandle(string key)
{
// Not a real implementation, here you would do your actual check if this service can be used
return key.Contains("-command-line");
}
}
public class PowerShellArgumentParserHandler : IHandler<string, IArgumentParser>
{
private readonly PowerShellArgumentParser _service;
public PowerShellArgumentParserHandler(PowerShellArgumentParser service)
{
_service = service;
}
public IArgumentParser GetService()
{
return _service;
}
public bool CanHandle(string key)
{
// Not a real implementation, here you would do your actual check if this service can be used
return key.Contains("-Version");
}
}
public static class DependencyConfig
{
public static Container Container { get; set; }
public static DependencyConfig()
{
Container = new Container();
Container.RegisterManyForOpenGeneric(typeof(IServiceFactory<,>), Assembly.GetExecutingAssembly());
Container.RegisterAll<IHandler<string, IArgumentParser>>(typeof(PowerShellArgumentParserHandler), typeof(CommandLineArgumentParserHandler));
// Whatever other config you need
Container.Verify();
}
}
public interface IArgumentParser
{
IDictionary<string, string> Parse(string data);
}
public class CommandLineArgumentParser : IArgumentParser
{
public IDictionary<string, string> Parse(string data)
{
// Not implemented, here for demonstraton purposes
throw new System.NotImplementedException();
}
}
public class PowerShellArgumentParser : IArgumentParser
{
public IDictionary<string, string> Parse(string data)
{
// Not implemented, here for demonstraton purposes
throw new System.NotImplementedException();
}
}
public interface IServiceFactory<in TKey, out TService>
{
TService Get(TKey key);
}
public interface IHandler<in TKey, out TService>
{
TService GetService();
bool CanHandle(TKey key);
}
public class ServiceFactory<TKey, TService> : IServiceFactory<TKey, TService>
{
private readonly IEnumerable<IHandler<TKey, TService>> _services;
public ServiceFactory(IEnumerable<IHandler<TKey, TService>> services)
{
_services = services;
}
public TService Get(TKey key)
{
return (from service in _services
where service.CanHandle(key)
select service.GetService()).Single();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment