如何在ASP.NET框架中配置Owin启动类中的服务

frebpwbc  于 2023-03-20  发布在  .NET
关注(0)|答案(3)|浏览(123)
public void Configuration(IAppBuilder app) 
{
    // code is executed 
}

public void ConfigureServices(IServiceCollection services) 
{
    // code is not executed  
}
slmsl1lt

slmsl1lt1#

ConfigureServices(IServiceCollection服务)方法仅在ASP.NET核心中可用。这可能会有所帮助-ASP.NET Classic OWIN StartUp ConfigureServices not called

svmlkihl

svmlkihl2#

基于OWIN Startup Class Detection,您必须添加NuGet包Microsoft.Owin.Host.SystemWeb,然后从VisualStudio模板引用OWIN Startup类,然后在以下代码中可以访问OWIN:

[assembly: OwinStartup("ProductionConfiguration", typeof(StartupDemo.ProductionStartup2))]

namespace StartupDemo
{
    public class ProductionStartup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Run(context =>
            {
                string t = DateTime.Now.Millisecond.ToString();
                return context.Response.WriteAsync(t + " Production OWIN App");
            });
        }
    }
    public class ProductionStartup2
    {
        public void Configuration(IAppBuilder app)
        {
            app.Run(context =>
            {
                string t = DateTime.Now.Millisecond.ToString();
                return context.Response.WriteAsync(t + " 2nd Production OWIN App");
            });
        }
    }
}
ymzxtsji

ymzxtsji3#

用这个

public void Configuration(IAppBuilder app)
   {
        TimedBackgroundService timedBackground = new TimedBackgroundService();
        timedBackground.StartAsync(CancellationToken.None);
   }

public class TimedBackgroundService : BackgroundService
 {
  private async Task ExecuteTaskAsync()
  {
    //code Here
  }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
    try
    {
        TimeSpan interval = TimeSpan.FromMinutes(1);
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(interval, stoppingToken);
            await ExecuteTaskAsync();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
  }
}

相关问题