Example #1
0
    public override void Execute()
    {
        InternalLogDebug = (s, l) => LogDebug(s);
        Logger           = new WeaverLogger(this);

        try
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            Logger.Debug($"Starting AutoDI Weaver v{GetType().Assembly.GetCustomAttribute<AssemblyVersionAttribute>()?.Version}", DebugLogLevel.Default);

            var typeResolver = new TypeResolver(ModuleDefinition, ModuleDefinition.AssemblyResolver, Logger);

            Settings settings = LoadSettings(typeResolver);
            if (settings == null)
            {
                return;
            }

            ICollection <TypeDefinition> allTypes = typeResolver.GetAllTypes(settings, out AssemblyDefinition autoDIAssembly);

            Logger.Debug($"Found types:\r\n{string.Join("\r\n", allTypes.Select(x => x.FullName))}", DebugLogLevel.Verbose);

            if (autoDIAssembly == null)
            {
                autoDIAssembly = ResolveAssembly("AutoDI");
                if (autoDIAssembly == null)
                {
                    Logger.Warning("Could not find AutoDI assembly");
                    return;
                }
                else
                {
                    Logger.Warning($"Failed to find AutoDI assembly. Manually injecting '{autoDIAssembly.MainModule.FileName}'");
                }
            }

            LoadRequiredData();

            ICodeGenerator gen = GetCodeGenerator(settings);

            if (settings.GenerateRegistrations)
            {
                Mapping mapping = Mapping.GetMapping(settings, allTypes, Logger);

                Logger.Debug($"Found potential map:\r\n{mapping}", DebugLogLevel.Verbose);

                ModuleDefinition.Types.Add(GenerateAutoDIClass(mapping, settings, gen, out MethodDefinition initMethod));

                if (settings.AutoInit)
                {
                    InjectInitCall(initMethod);
                }
            }
            else
            {
                Logger.Debug("Skipping registration", DebugLogLevel.Verbose);
            }

            //We only update types in our module
            foreach (TypeDefinition type in allTypes.Where(type => type.Module == ModuleDefinition))
            {
                ProcessType(type, gen);
            }
            gen?.Save();
        }
        catch (Exception ex)
        {
            var sb = new StringBuilder();
            for (Exception e = ex; e != null; e = e.InnerException)
            {
                sb.AppendLine(e.ToString());
            }
            Logger.Error(sb.ToString());
        }
        finally
        {
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainOnAssemblyResolve;
        }
    }