【问题标题】:Exception logging in WPF Application, MVVMLight SimpleIoC hides exception instead of throwing themWPF应用程序中的异常记录,MVVMLight SimpleIoC隐藏异常而不是抛出它们
【发布时间】:2014-01-27 19:46:25
【问题描述】:

我有一个 LoB WPF 应用程序,需要找到一种方法来全局处理和记录异常。

知道我在做这样的事情:

public partial class App : Application
{
        public App()
        {
           this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
        }

        void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
           string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
           MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
           e.Handled = true;
        }
}

问题是 SimpleIoC “吃掉” ViewModel 中抛出的异常。 示例:

public class TestViewModel : ViewModelBase
{
    public TestViewModel()
    {
        throw new Exception("this exception will be catched by SimpleIoC, therefore i'm not able to handle it elsewhere");
    }
}

我正在使用如下所示的 MVVMLight ViewModelLocator:

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        SimpleIoc.Default.Register<TestViewModel>();
    }

    public TestViewModelTestViewModel
    {
        get
        {
            return ServiceLocator.Current.GetInstance<TestViewModel>();
        }
    }

    public static void Cleanup()
    {
        SimpleIoc.Default.Unregister<TestViewModel>();
    }
}

根据this article 和this article 关于异常处理的说法,像这样捕获(并吞下)异常是不好的设计,因为它可能会隐藏应用程序中的错误。但我可能会弄错。

最后,这是我的问题: 如何记录在构建 ViewModel 期间发生的异常?


底线: MVVMLight 真的很棒,我喜欢它!感谢 Laurent Bugnion 以及迄今为止为这个项目做出贡献的每一个人。

【问题讨论】:

  • 嗨@Joel,这个问题有什么更新吗?
  • 没有。我没有找到解决方案。也许@lbugnion aka Laurent Bugnion 知道答案。

标签: c# wpf exception-handling mvvm-light ioc-container


【解决方案1】:

我记录了这样一个事实,即 SimpleIoc 似乎将构造函数中发生的异常作为 codeplex 上的错误吃掉了。

您可以在此处查看项目状态:https://mvvmlight.codeplex.com/workitem/7681

更新

我做了更多的测试,得出的结论是这不是 SimpleIoc 的问题,但实际上是 WPF 如何在绑定属性中隐藏异常的症状(在这种情况下,绑定的“Te​​stViewModelTestViewModel”属性ViewModelLocator 类)。

使用 SimpleIoc 获取 TestViewModel 的实例在 WPF 视图/控件之外会导致抛出异常(如预期的那样)。然后它会被当时的任何处理程序捕获。

另一方面,通过 SimpleIoc 在绑定属性中获取 TestViewModel 的实例只会导致绑定失败,但该异常似乎并未“升级”到 WPF 内部之外。调试时将异常写入输出窗口,但这在测试/生产环境中用处不大。

所以,简而言之,我不认为 SimpleIoc 正在掩埋异常(相反,它是“WPF 事物”)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2015-10-26
    相关资源
    最近更新 更多