使用 Lamar 引导 C# 服务时如何调试和查找错误 "NullReferenceException" 的来源?

How to debug and find source of the error "NullReferenceException" when bootstrapping C# services using Lamar?

我们的项目中有一些服务最近移植到了 .NetCore 3.0。此外,由于 StructureMap 即将停用,我们删除了所有引用并移至 Lamar,因为它是迁移到的最快的。引导时,其中一项服务抛出 "System.NullReferenceException: 'Object reference not set to an instance of an object"。当然,我为 Lamar 重写了注册表 类。 我无法在 Lamar 中找到任何有用的诊断方法来查找错误的来源。请让我知道是否有人可以指导我如何捕获错误源,因为现在调用堆栈只提供 Bootstrap init 调用作为错误源。 我们在程序集名称中查找具有特定字符串的所有程序集,例如:"Project-Name"

var container = new Container(x =>
                    x.Scan(y =>
                    {
                        // Scan all DLLs for Registries
                        y.AssembliesFromApplicationBaseDirectory(
                                assembly =>
                                {
                                     if (assembly.FullName.Contains("Project-Name"))
                                    {
                                        return true;
                                    }
                                    return false;
                                });

                        y.LookForRegistries();

                    }));

我不知道这是否正确,但我想回答我自己的问题以将其标记为已关闭。我必须一个一个地构建我的项目,一个一个地注册它们以找到导致问题的项目。

只是想添加更多信息以防对某人有帮助。 "container.AssertConfigurationIsValid()" 仅在容器初始化成功时才有用。对我来说,Container init 本身正在崩溃。所以 Assert 根本没用。

但如果容器已初始化但 IoC 调用失败或出现 "XYZInterface is not registered within this container and cannot be auto discovered by any missing family policy" 之类的错误,则可以通过在容器运行时值上设置 Watch 并检查 ErrorMessages 属性 是否有值来识别这些错误.这将使您更深入地了解实际破坏服务初始化的原因。在即时 window 中,您可以检查每个实例的 ErrorMessage 值。

例如:要检查列表中第一个实例的错误消息值,请检查

((Lamar.InstanceRef[])((Lamar.QueryModel)container.Model).AllInstances)[0].Instance.ErrorMessages. 

这将有助于确定其他重大问题。