예제 #1
0
        /// <summary>
        /// Build Service
        /// </summary>
        /// <param name="build"></param>
        public static void Build(Action <ServiceCollection> build)
        {
            var serviceCollection = new ServiceCollection();

            build(serviceCollection);

            ServiceProvider = serviceCollection.BuildServiceProvider();
        }
예제 #2
0
        /// <summary>
        /// 根据指定类型/接口类型 创建实例
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="type"></param>
        /// <param name="implementationType"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static object CreateInstance(Interface.IServiceProvider serviceProvider, Type type, Type implementationType, params object[] args)
        {
            if (type.IsInterface && implementationType == null)
            {
                implementationType = FindImplementationType(type);
            }

            var constructors = implementationType.GetConstructors().OrderBy(m => m.GetParameters().Length);

            foreach (var item in constructors)
            {
                var parameters = item.GetParameters();
                var flag       = true;

                var ctorArgs = new object[parameters.Length];

                for (int i = 0; i < parameters.Length; i++)
                {
                    var parameter = parameters[i];

                    if (args.Any(m => parameter.ParameterType.IsAssignableFrom(m.GetType())))
                    {
                        ctorArgs[i] = args.First(m => parameter.ParameterType.IsAssignableFrom(m.GetType()));

                        continue;
                    }

                    var serviceInstance = serviceProvider.GetService(parameter.ParameterType);

                    if (serviceInstance != null)
                    {
                        ctorArgs[i] = serviceInstance;

                        continue;
                    }

                    flag = false;

                    break;
                }

                if (flag)
                {
                    var instance = CreateInstance(implementationType, ctorArgs);
                    return(instance);
                }
            }

            throw new MissingMethodException("创建" + implementationType.Name + "失败,因为没有找到合适的构造函数参数");
        }
 public static T GetService <T>(this Interface.IServiceProvider provider)
 {
     return((T)provider.GetService(typeof(T)));
 }