Skip to content

Instantly share code, notes, and snippets.

@melvinlee
Created August 4, 2015 07:26
Show Gist options
  • Save melvinlee/1b0de12cdf10b2de8023 to your computer and use it in GitHub Desktop.
Save melvinlee/1b0de12cdf10b2de8023 to your computer and use it in GitHub Desktop.
Register typeof T with named services
using System;
using System.Collections.Generic;
using System.Reflection;
namespace CallCosting.Reporting
{
public class ReportFactory
{
public ReportFactory()
{
Register(Assembly.GetExecutingAssembly());
}
private static readonly Dictionary<string, Type> Registrations = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Scan and register all specified assemblies after report .
/// </summary>
private void Register(params Assembly[] assemblies)
{
var reportType = typeof(IReport);
foreach (var assembly in assemblies)
{
foreach (var type in assembly.GetTypes())
{
if (!reportType.IsAssignableFrom(type) )
continue;
Registrations.Add(type.Name, type);
}
}
}
/// <summary>
/// Create some report!
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IReport Create(string name)
{
Type type;
if (!Registrations.TryGetValue(name, out type))
throw new ArgumentException("Failed to find report named '" + name + "'.");
return (IReport)Activator.CreateInstance(type);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment