Created
August 4, 2015 07:26
-
-
Save melvinlee/1b0de12cdf10b2de8023 to your computer and use it in GitHub Desktop.
Register typeof T with named services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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