【问题标题】:I cant seem to use dependency injection in WinRT BackgroundTask我似乎无法在 WinRT BackgroundTask 中使用依赖注入
【发布时间】:2013-03-01 15:37:54
【问题描述】:

我正在 Windows 运行时组件中实现 IBackgroundTask,我想向其中注入一个记录器依赖项,但应用程序在调用后台任务时退出。它甚至不会进入构造函数。我使用 Ninject 作为 DI 容器,在应用程序的其他任何地方使用它都没有问题。

我想做这样的事情:

private readonly ILog _logger;

public BackroundTask(ILog logger)
{
    _logger = logger;
}

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        var deferral = taskInstance.GetDeferral();

        try
        {
            // do something here
        }
        catch (Exception ex)
        {
            // log the error with injected logger...
            logger.ErrorFormat("{0}Error in QueueTimer {1}{0}",
                Environment.NewLine, ex.ToString());
        }

        deferral.Complete();
    }

我尝试过的任何事情都没有成功,现在只需登录调用 .cs 文件中的 OnComplete 方法。

【问题讨论】:

  • ILOG 必须经过编译才能支持 WinRT。究竟是什么错误?
  • 在不相关的注释中,async void 通常应避免使用,但事件处理程序除外。您可能有充分的理由这样做,但如果您不这样做,则需要考虑一些事情。
  • 我正在使用将数据发送回服务器的异步调用,然后我需要记录发送的成功或失败。
  • ILog 被编译为 Windows 运行时组件。事件日志中的错误是:激活应用程序 a.Winrt.Ui_tjekt9a7fmk0j!App for the Windows.BackgroundTasks contract failed with error: Not implemented

标签: c# dependency-injection background windows-runtime


【解决方案1】:

根据我创建 Windows 应用商店应用程序的有限经验,您必须为后台任务提供默认构造函数;不会调用任何其他构造函数。

不过,希望我错了;能够传递后台任务的依赖项是可行的,但我不确定这是否有意义,因为您自己的代码甚至可能在任务开始时都没有运行。我认为在程序和任务之间进行通信的唯一方法是使用永久存储。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    相关资源
    最近更新 更多