I've been looking around on SO for a while and can't find the answer to my particular question:
How do you use Autofac to inject data (via constructor or property) into the OWIN Startup class?
I'm using Autofac in a Windows service which also handles creation of back-end services etc. so I'm doing all the configuration reading and container building in there.
I want to be able to register the Startup class so I can inject allowed origins for CORS but even when I register the object with a property like so:
var builder = new ContainerBuilder();
// This will actually be read from config.
var origins = new[]
{
"http://localhost",
"http://localhost:8082",
};
builder.Register(c => new Startup(origins));
var container = builder.Build();
At runtime when the Startup class is instantiatedthe callstack shows it comes from external code and my Autofac builder didn't push the property in.
I'd ideally like to keep my Autofac registrations in a single place (the Windows service class) and just inject the required data to Startup so I can just do something like this below (where allowedOrigins
is set as a property or injected via the constructor)
public void Configuration(IAppBuilder app)
{
var configuration = new HttpConfiguration();
...
var origins = string.Join(",", allowedOrigins);
var cors = new EnableCorsAttribute(origins, "*", "*") { SupportsCredentials = true };
configuration.EnableCors(cors);
....
}
Any ideas would be much appreciated. Thanks
peteski
UPDATE
I should add that after attempting Autofac registration and building, I was kicking off the OWIN self host app by doing:
var webApp = WebApp.Start<Startup>(baseAddress);
From a conversation with a friend they suggested creating the Startup
object and passing it to the WebApp
:
var startup = new Startup(origins);
var webApp = WebApp.Start(startup, baseAddress);
Here, I'd add the IEnumerable<string>
origins to the ctor for the Startup
class. This does actually work! But feels like it goes around using Autofac to handle giving the Startup class what it needs.