using Autofac; using Autofac.Extras.DynamicProxy; using Microsoft.Extensions.DependencyModel; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Text; using System.Threading.Tasks; using WIDESEAWCS_Core.AOP; using WIDESEAWCS_Core.BaseRepository; using WIDESEAWCS_Core.BaseServices; using WIDESEAWCS_Core.Helper; using WIDESEAWCS_Core.LogHelper; namespace WIDESEAWCS_Core.Extensions { public class AutofacModuleRegister : Autofac.Module { protected override void Load(ContainerBuilder builder) { var basePath = AppContext.BaseDirectory; var cacheType = new List(); //builder.RegisterType(); //cacheType.Add(typeof(LogAOP)); builder.RegisterGeneric(typeof(RepositoryBase<>)).As(typeof(IRepository<>)).InstancePerDependency();//注册仓储 builder.RegisterGeneric(typeof(ServiceBase<,>)).As(typeof(IService<>)).InstancePerDependency();//注册服务 Type baseType = typeof(IDependency); List compilationLibrary = DependencyContext.Default .RuntimeLibraries .Where(x => !x.Serviceable && x.Type == "project") .ToList(); List assemblyList = new List(); foreach (var library in compilationLibrary) { try { string path = Path.Combine(basePath, $"{library.Name}.dll"); if (!File.Exists(path)) { var msg = $"{library.Name}.dll丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。"; //log.Error(msg); throw new Exception(msg); } assemblyList.Add(Assembly.LoadFrom(path)); } catch (Exception ex) { Console.WriteLine(library.Name + ex.Message); } } builder.RegisterAssemblyTypes(assemblyList.ToArray()).Where(x => !x.IsInterface && !x.IsAbstract && baseType.IsAssignableFrom(x)) .AsImplementedInterfaces() .PropertiesAutowired() .InstancePerDependency(). EnableInterfaceInterceptors() .InterceptedBy(cacheType.ToArray()); builder.RegisterType().As() .AsImplementedInterfaces() .InstancePerLifetimeScope() .PropertiesAutowired(); builder.RegisterType().InstancePerLifetimeScope(); } } }