MVC:在应用程序启动时运行一个方法,而不从Application_Start调用它

本文关键字:方法 Application 调用 Start 一个 启动 应用程序 运行 MVC | 更新日期: 2023-09-27 18:00:12

我有一个类,它有一个方法,应该在应用程序启动时运行。我不想直接从Application_Start事件调用此方法。让这个类实例化并在application_start上运行方法的最佳方法是什么?

换句话说,我想将这些代码注入到应用程序启动中。

MVC:在应用程序启动时运行一个方法,而不从Application_Start调用它

我注意到有些人使用WebActivatorEx.PostApplicationStartMethod。我没有深入研究细节,但这是我首先要看的地方。下面是一个注册为在调用RegisterBundles时自动运行的类的示例。另一个钩子可能就是你要找的。

[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(BootstrapBundleConfig), "RegisterBundles")]
namespace Deloitte.EmploymentMemo.Presentation.App_Start
{
    public class BootstrapBundleConfig
    {
        public static void RegisterBundles()
        {
            // Add @Styles.Render("~/Content/bootstrap") in the <head/> of your _Layout.cshtml view
            // For Bootstrap theme add @Styles.Render("~/Content/bootstrap-theme") in the <head/> of your _Layout.cshtml view
            // Add @Scripts.Render("~/bundles/bootstrap") after jQuery in your _Layout.cshtml view
            // When <compilation debug="true" />, MVC4 will render the full readable version. When set to <compilation debug="false" />, the minified version will be rendered automatically
            BundleTable.Bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));
            BundleTable.Bundles.Add(new StyleBundle("~/Content/bootstrap").Include("~/Content/bootstrap.css"));
            BundleTable.Bundles.Add(new StyleBundle("~/Content/bootstrap-theme").Include("~/Content/bootstrap-theme.css"));
        }
    }
}

使用OWIN启动的可能解决方案之一。

安装nuget包:install-package Microsoft.Owin.Host.SystemWeb

添加到appsettings启动类:

   <appSettings>
          <add key="owin:appStartup" value="MyProject.Code.Startup" />
   </appSettings>

按照惯例,您需要一个名为Configuration:的方法类

    public class Startup
    {
            public void Configuration(IAppBuilder app)
            {
                app.Run(context =>
                {
                    string t = DateTime.Now.Millisecond.ToString();
                    return context.Response.WriteAsync(t + " Production OWIN App");
                });
            }
    }

或者做任何你需要的事。

如果你对此感兴趣,请查看asp.net:OWIN和Katana项目

使用委托。它们包含对方法的引用,使您可以同时调用一些方法;使用委托的示例:

public delegate void myDelegate();
private static void Main()
{
    myDelegate myFunctions = Method1; //initialize delegate with Method1
    myFunctions += Method2;           //Add Method2 to delegate
    myFunctions(); //call all methods added to delegate
}
public static void Method1()
{
    Console.WriteLine("Hello from method1");
}
public static void Method2( )
{
    Console.WriteLine("Hello from method2");
}

这将调用Method1和Method2