Pass a parameter to OWIN host

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-21 08:00:52

问题


I'm self-hosting ASP.NET Web API and SignalR using OWIN. I start the server (on a console app) with this code:

using (WebApplication.Start<Startup>(url))
{
    Console.WriteLine("Running...");
    Console.ReadLine();
}

This works fine. But now I need to pass a parameter (an object) to the Startup class. How can this be done?


回答1:


The WebApplication.Start method has an overload that accepts a IServiceProvider as parameter, so it is possible to inject the data I want.

IServiceProvider serviceProvider = DefaultServices.Create(defaultServiceProvider =>
{
    defaultServiceProvider.AddInstance<IMyInterface>(myInstance);
});

using (WebApplication.Start<Startup>(serviceProvider, url)){ ... }

Now, on my Startup class I only need to create a constructor that receives the IMyInterface:

public Startup(IMyInterface myInstance)
{
    ...
}



回答2:


You can use the WebApp.Start Method (String, Action<IAppBuilder>) overload.

Example:

using (WebApplication.Start(url, appBuilder => new Startup(myObject).Configuration(appBuilder)))
{
    Console.WriteLine("Running...");
    Console.ReadLine();
}


来源:https://stackoverflow.com/questions/15511651/pass-a-parameter-to-owin-host

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!