如何订阅Nancyfx中的ApplicationStartup事件?

时间:2014-07-21 12:41:48

标签: nancy

我正在为Nancy构建一个扩展,我不确定在哪里可以挂钩Nancy的ApplicationStartup事件。

1 个答案:

答案 0 :(得分:3)

如果要在安装库时自动运行某些代码,则需要继承Nancy类IApplicationStartup并编写实现。

https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Bootstrapper/IApplicationStartup.cs

例如,对于Nancy.Raygun,我会执行以下操作:

public class NancyRaygunRegistration : IApplicationStartup
{
    private static readonly RaygunClient Client;

    static NancyRaygunRegistration()
    {
        var apiKey = RaygunSettings.Settings.ApiKey;

        if (string.IsNullOrWhiteSpace(apiKey))
        {
            apiKey = ConfigurationManager.AppSettings["nr.apiKey"];
        }

        if (apiKey == null) return;

        Client = new RaygunClient(apiKey);
    }

    public void Initialize(IPipelines pipelines)
    {
        if (Client == null) return;

        var raygunItem = new PipelineItem<Func<NancyContext, Exception, Response>>("Raygun", (context, exception) =>
        {
            Client.SendInBackground(context, exception);

            return null;
        });

        pipelines.OnError.AddItemToStartOfPipeline(raygunItem);
    }
}

Nancy将自动查找IAppliationStartup的所有实现并运行它们。

需要考虑的其他事项:

IRegistrations https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Bootstrapper/IRegistrations.cs

IRequestStartup https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Bootstrapper/IRequestStartup.cs

IPipelines https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Bootstrapper/IPipelines.cs