0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.