I'm writing a basic c# class for custom IOC container with two Public methods Register() & Resolve() and one private Method CreateInstance()
below is my code.
In the below Code, CreateInstance() method, i'm getting syntax error to Resolve the dependencies (commented line), without using Generics I could resolve the dependencies and it works fine, while using generics for default typecasting I'm getting syntax error
Can anyone help me on this Commented Line?
public class Container
{
static Dictionary<Type, Func<object>> registrations = new Dictionary<Type, Func<object>>();
public static void Register<TService, TImpl>() where TImpl : TService
{
registrations.Add(typeof(TService), () => Resolve<TImpl>());
}
public static T Resolve<T>()
{
var serviceType = typeof(T);
Func<object> creator;
if (registrations.TryGetValue(serviceType, out creator)) return (T)creator();
if (!serviceType.IsAbstract) return CreateInstance<T>();
else throw new InvalidOperationException("No registration for " + serviceType);
}
private static T CreateInstance<T>()
{
var implementationType = typeof(T);
var ctor = implementationType.GetConstructors().Single();
var parameterTypes = ctor.GetParameters().Select(p => p.ParameterType);
//var dependencies = parameterTypes.Select(Resolve).ToArray();
return (T)Activator.CreateInstance(implementationType, dependencies);
}
}