How to debug Unity resolution?

后端 未结 3 1964
离开以前
离开以前 2021-02-19 01:42

In a WPF project(with prism) we are using Unity as DI framework.

Recently, after we merged two big branches, we were not able to start our application, we w

3条回答
  •  悲哀的现实
    2021-02-19 02:06

    If You are using Unity v5+ and are too lazy to look up what changed from v4 to v5, then you can copy my version:

    using System.Reflection;
    using Unity.Extension;
    using Unity.Builder;
    using Unity.Strategies;
    
    namespace Company.ProjectName.Shared.Bootstrap.Unity
    {
        public class LogResolvesUnityContainerExtension : UnityContainerExtension
        {
            private static readonly ILogger Logger = LoggerManager.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType);
            
            protected override void Initialize()
            {
                Context.Strategies.Add(new LoggingStrategy(Logger), UnityBuildStage.PreCreation);
            }
    
            private class LoggingStrategy : BuilderStrategy
            {
                private readonly ILogger _logger;
                
                public LoggingStrategy(ILogger logger)
                {
                    _logger = logger;
                }
    
                public override void PreBuildUp(ref BuilderContext context)
                {
                    // Be aware that for Singleton Resolving this log message will only be logged once, when the Singleton is first resolved. After that, there is no buildup and it is just returned from a cache.
                    
                    var registrationType = context.RegistrationType; 
                    var registrationName = context.Name;
                    var resolvedType = context.Type;
                    
                    var registrationNameWithParenthesesOrNothing = string.IsNullOrEmpty(registrationName) ? "" : $"({registrationName})";
                    _logger.LogDebug($"Resolving [{registrationType}{registrationNameWithParenthesesOrNothing}] => [{resolvedType}]");
                }
            }
        }
    }
    

    Credit still goes to Haukinger for writing the v4 original version.

提交回复
热议问题