问题
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);
}
回答1:
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);
});
回答2:
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;
}
来源:https://stackoverflow.com/questions/23258282/hw-to-pass-arguments-to-my-own-startup-class