I'm trying to develop a web api self hosting app using OWIN. In my own XyzStartup class, I need an external argument: contentFolderPath.
However, I didn't find a way to pass this argument. Here is my code below:
var contentFolderPath = this.TextBox.Text; // user input
var startOptions = new StartOptions();
using(WebApp.Start<XyzStartup>(startOptions)){
}
My startup
public class XyzStartup
{
XyzStartup(string contentFolderPath) { ... }
}
I noticed there is a StartOption class, but don't how to use it. Can I use it in my XyzStartup class?
Thanks in advance!
I finally find a way to do this:
var startOptions = new StartOptions();
startOptions.Urls.Add('..some url ..');
WebApp.Start(startOptions, (appBuilder)=>{
new XyzStartup(contentFolderPath).Configuration(appBuilder);
}
If you want to pass parameter to StartUp class, you can use Action<IAppBuilder>
in WebApp.Start like Cillié Malan mentioned in the comment instead of launching with Type parameter(WebApp.Start<T>
)
Here is a concrete example for self-hosting:
object someThingYouWantToAccess;
var server = WebApp.Start("http://localhost:8080/", (appBuilder) =>
{
// You can access someThingYouWantToAccess here
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
});
As far as I can tell, though it may have been possible before, it is not possible to pass parameters to the startup class.
However, when self hosting, I noticed that the startup class is created in the same thread that calls WebApp.Start
. With this in mind I used a ThreadStatic
field to pass information to the startup class (in my case I wanted to pass HttpConfiguration
):
public class Startup
{
private HttpConfiguration _configuration;
[ThreadStatic]
internal static HttpConfiguration _configurationHolder;
public static HttpConfiguration CurrentConfiguration
{
get { return _configurationHolder; }
set { _configurationHolder = value; }
}
public Startup()
{
//get the configuration which is held in a threadstatic variable
_configuration = _configurationHolder;
}
public void Configuration(IAppBuilder appBuilder)
{
//do stuff
}
}
And then elsewhere I have another method that starts the self-hosted site:
public void Start(StartOptions startupOptions, HttpConfiguration configuration)
{
Startup.CurrentConfiguration = configuration;
_application = WebApp.Start<Startup>(startupOptions);
Startup.CurrentConfiguration = null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With