ServiceStack Messaging API:在 OnAfterInit 中使用 HostContet.AppHost.ExecuteMessage 给出 NullReferenceException

ServiceStack Messaging API: Using HostContet.AppHost.ExecuteMessage in OnAfterInit gives NullReferenceException

如前所述,我有时使用这种方法在内部执行服务:

IMessage theMessage = new Message<Startup>(new Startup());
var reply = HostContext.AppHost.ExecuteMessage(theMessage); // The way to get the pipeline to execute when we do internal call, and get DI to work etc

这很好用并且符合预期,除了一种情况:当我从 OnAfterInit 方法调用它时,我覆盖了它。

我的想法是,我想在 AppHost 准备就绪时执行一些启动操作,在初始化之后,但是在执行此操作时,它失败并显示 NullReferenceException:

public override void OnAfterInit()
{
    base.OnAfterInit();

    IMessage theMessage = new Message<Startup>(new Startup());
    var reply = HostContext.AppHost.ExecuteMessage(theMessage); 
}

错误:

   at ServiceStack.ServiceStackHost.<ApplyRequestConvertersAsync>d__361.MoveNext() in C:\BuildAgent\work81147c480f4a2f\src\ServiceStack\ServiceStackHost.Runtime.cs:line 45
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at ServiceStack.Host.ServiceController.ExecuteMessage(IMessage dto, IRequest req) in C:\BuildAgent\work81147c480f4a2f\src\ServiceStack\Host\ServiceController.cs:line 584
   at ServiceStack.ServiceStackHost.ExecuteMessage(IMessage mqMessage) in C:\BuildAgent\work81147c480f4a2f\src\ServiceStack\ServiceStackHost.cs:line 1486
   at Test.Test.OnAfterInit() in C:\Git\Test\Test.cs:line 59

似乎还没有全部初始化和就绪。如果我这样做,它会起作用:

public override void OnAfterInit()
{
    base.OnAfterInit();
    System.Threading.Timer t = new System.Threading.Timer((o) => 
    {
        IMessage theMessage = new Message<Startup>(new Startup());
        var reply = HostContext.AppHost.ExecuteMessage(theMessage);
    }, null, 100, int.MaxValue);
}

我很想知道我是否遗漏了什么,以及是否有更好的方法来解决这个问题。定时器的东西可以用,但它不适合我。

理想情况下,执行服务应该在运行时完成,而不是在启动时完成,但如果您确实想要执行服务,则需要在启动结束时执行它们,此时 ServiceStack 的其余部分已经像 AfterInitCallbacks,例如:

AfterInitCallbacks.Add(host => 
    host.ExecuteMessage(new Message<Startup>(new Startup()));