I am trying to scope my services per on a per request basis, but my injected services always seem to be scoped to the parent/root container, and subsequent requests see the state from a previous request.
I've setup a custom StructureMap container in my startup class
// Wireup the container
Container = new Container();
Container.Configure(config =>
{
// register the dotnet framework registered services into our container
config.Populate(services);
// Import all the registries
config.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.LookForRegistries();
});
});
return Container.GetInstance<IServiceProvider>();
Register a service in a register as;
For<ITest>().Use<Test>().ContainerScoped();
Then wiredup the following middleware
var container = serviceProvider.GetRequiredService(typeof(IContainer)) as IContainer;
if (container != null)
{
using (var requestContainer = container.GetNestedContainer())
{
context.RequestServices = requestContainer.GetInstance<IServiceProvider>();
await _next.Invoke(context);
}
}
else
{
await _next.Invoke(context);
}
Any pointers as to what I am missing? Thanks
There's no need to wire up the RequestServices
property yourself. The ASP.NET host already does that for you. Just resolve what you need from the existing RequestServices
provider.