108 lines
2.6 KiB
C#
108 lines
2.6 KiB
C#
using Autofac;
|
|
using Autofac.Core;
|
|
using System;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MAX.Core.DependencyInjection;
|
|
|
|
/// <summary>
|
|
/// 容器
|
|
/// </summary>
|
|
public static partial class IocManager
|
|
{
|
|
/// <summary>
|
|
/// 默认容器
|
|
/// </summary>
|
|
public static IContainer Container { get; internal set; }
|
|
public static void SetContainer(IContainer container)
|
|
{
|
|
Container = container;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 确定指定的服务在上下文中是否可用。
|
|
/// </summary>
|
|
/// <typeparam name="TService"></typeparam>
|
|
/// <returns></returns>
|
|
public static bool IsRegistered<TService>()
|
|
{
|
|
return Container.IsRegistered<TService>();
|
|
}
|
|
/// <summary>
|
|
/// 确定指定的服务在上下文中是否可用。
|
|
/// </summary>
|
|
/// <param name="type"></param>
|
|
/// <returns></returns>
|
|
public static bool IsRegistered(Type serverType)
|
|
{
|
|
return Container.IsRegistered(serverType);
|
|
}
|
|
|
|
public static TService Resolve<TService>()
|
|
{
|
|
if (Container.IsRegistered<TService>())
|
|
{
|
|
return Container.Resolve<TService>();
|
|
}
|
|
return default;
|
|
}
|
|
public static object Resolve(Type serviceType)
|
|
{
|
|
if (Container.IsRegistered(serviceType))
|
|
{
|
|
return Container.Resolve(serviceType);
|
|
}
|
|
return default;
|
|
}
|
|
public static TService Resolve<TService>(params Parameter[] parameters)
|
|
{
|
|
if (Container.IsRegistered<TService>())
|
|
{
|
|
return Container.Resolve<TService>(parameters);
|
|
}
|
|
return default;
|
|
}
|
|
/// <summary>
|
|
/// 获取所有注册
|
|
/// </summary>
|
|
/// <typeparam name="TService"></typeparam>
|
|
/// <returns></returns>
|
|
public static TService[] ResolveAll<TService>()
|
|
{
|
|
return ResolveAll(typeof(TService)) as TService[];
|
|
}
|
|
/// <summary>
|
|
/// 获取所有注册
|
|
/// </summary>
|
|
/// <typeparam name="TService"></typeparam>
|
|
/// <returns></returns>
|
|
public static object[] ResolveAll(Type type)
|
|
{
|
|
Type enumerableOfType = typeof(IEnumerable<>).MakeGenericType(type);
|
|
return (object[])Container.ResolveService(new TypedService(enumerableOfType));
|
|
}
|
|
|
|
public static Type GetRegistrationType(string key)
|
|
{
|
|
foreach (IComponentRegistration registration in Container.ComponentRegistry.Registrations)
|
|
{
|
|
foreach (Service service in registration.Services)
|
|
{
|
|
if (service is KeyedService ks)
|
|
{
|
|
if (key.Equals(ks.ServiceKey.ToString(), StringComparison.Ordinal))
|
|
{
|
|
if (Container.ComponentRegistry.TryGetServiceRegistration(service, out ServiceRegistration serviceRegistration))
|
|
{
|
|
return serviceRegistration.Registration.Target.Activator.LimitType;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
}
|