簡體   English   中英

MVC:在Application啟動時運行方法,而不從Application_Start調用它

[英]MVC: Run a method on Application startup without calling it from Application_Start

我有一個類應該在應用程序啟動時運行。 我不想直接從Application_Start事件中調用此方法。 將這個類實例化並在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM