using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace QYZH.InteractiveMagazine.Infrastructure.Context
{
    /// <summary>
    /// 应用程序上下文
    /// </summary>
    public static class ServiceContext
    {
        public static IServiceProvider ServiceProvider;

        public static void UseServiceContext(this IApplicationBuilder applicationBuilder)
        {
            ServiceProvider = applicationBuilder.ApplicationServices;
        }

        public static void UseServiceContext(this IServiceCollection services)
        {
            ServiceProvider = services.BuildServiceProvider();
        }

        /// <summary>
        /// 获取对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
            return ServiceProvider.GetService<T>();
        }

        /// <summary>
        /// 获取Scope对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetScopeService<T>()
        {
            var scope = ServiceProvider.CreateScope();
            return scope.ServiceProvider.GetService<T>();
        }

        /// <summary>
        /// 获取对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetRequiredService<T>()
        {
            return ServiceProvider.GetRequiredService<T>();
        }

        /// <summary>
        /// 获取对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetOptionsMonitor<T>()
        {
            return ServiceProvider.GetService<IOptionsMonitor<T>>().CurrentValue;
        }

        /// <summary>
        /// 获取对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetOptions<T>() where T : class, new()
        {
            return ServiceProvider.GetService<IOptions<T>>().Value;
        }
    }
}