Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a parameter to OWIN host

Tags:

c#

owin

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?

like image 468
Leo Avatar asked Mar 19 '13 22:03

Leo


2 Answers

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)
{
    ...
}
like image 182
Leo Avatar answered Sep 19 '22 13:09

Leo


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();
}
like image 22
Owen Pauling Avatar answered Sep 20 '22 13:09

Owen Pauling