Creating Custom Container Class in c#

2019-07-23 06:24发布

问题:

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);
    }
}

回答1:

I know this is a post from a while ago however if anyone is wondering how they could dynamically pass a type you can do it with reflection using the code below:

        var dependencies = parameterTypes.Select(paramType => typeof(Container).GetMethod("Resolve")?.MakeGenericMethod(paramType).Invoke(null, null)).ToArray();            

This will find the Resolve method, use the parameter type as it's generic type, and then invoke it with no arguments.