在C#中创建自定义容器类

在C#中创建自定义容器类

本文介绍了在C#中创建自定义容器类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为自定义IOC容器编写一个基本的c#类,其中包含两个Public方法Register()&我下面的代码是Resolve()和一个私有方法CreateInstance()

I'm writing a basic c# class for custom IOC container with two Public methods Register() & Resolve() and one private Method CreateInstance()

在下面的代码中, CreateInstance()方法,我在不使用泛型的情况下获取语法错误来解决依赖关系(注释行),我可以解决依赖关系,并且工作正常,而在将泛型用于默认类型转换时,我遇到了语法错误

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


推荐答案

I知道这是前一阵子的帖子,但是如果有人想知道如何动态传递类型,可以使用下面的代码进行反射:

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

这将找到Resolve方法,将参数类型用作通用类型,然后使用没有参数。

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

这篇关于在C#中创建自定义容器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:05