using Autofac; using Autofac.Core; using Autofac.Integration.WebApi; using FreeSql; using MAX.Core.DependencyInjection; using MAX.Core.Helpers; using MAX.Core.Interfaces; using MAX.Core.Logger; using MAX.Framework.Logger; using Store.Framework.Commons; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Store.Framework.DependencyInjection; public class ContainerConfig { public static IContainer BuildContainer() { var builder = new ContainerBuilder(); var appAssembly = StoreAppTypeFinder.Current.GetAssemblies().ToArray(); var connection = ConfigurationManager.ConnectionStrings["ConnKJD"]; if (connection == null || string.IsNullOrWhiteSpace(connection.ConnectionString)) { throw new ConfigurationErrorsException("未配置连接字符串:ConnKJD"); } // ImageCacheService 使用独立的 imagecache 数据库。 builder.Register(_ => { return new FreeSqlBuilder() .UseConnectionString( DataType.MySql, connection.ConnectionString) .Build(); }) .As() .SingleInstance(); // 注册 Web API 所有 Controller builder.RegisterApiControllers(appAssembly); builder.RegisterInstance(NLogger.Instance).As().SingleInstance(); #region 注册所有IOC接口 Type typeSingleton = typeof(ISingletonDependency); builder.RegisterAssemblyTypes(appAssembly) .Where(a => typeSingleton.IsAssignableFrom(a) && a.IsClass && !a.IsAbstract ) .AsImplementedInterfaces() .AsSelf() .SingleInstance(); Type typeTransient = typeof(ITransientDependency); builder.RegisterAssemblyTypes(appAssembly) .Where(a => typeTransient.IsAssignableFrom(a) && a.IsClass && !a.IsAbstract ) .AsImplementedInterfaces() .AsSelf() .InstancePerDependency(); Type typeScoped = typeof(IScopedDependency); builder.RegisterAssemblyTypes(appAssembly) .Where(a => typeScoped.IsAssignableFrom(a) && a.IsClass && !a.IsAbstract) .AsImplementedInterfaces() .AsSelf() .InstancePerRequest(); #endregion IServiceRegistrar registrar = new ServiceRegistrarProxy(builder); IEnumerable startupList = ReflectionHelper.GetInstancesByInterface(appAssembly); foreach (IStartup item in startupList.OrderByDescending(a => a.Priority)) { Debug.WriteLine($"Startup : {item.GetType()}"); item.Initialize(); item.Register(registrar); } var app = builder.Build(); return app; } }