Getting a scoped component from a IDocumentStoreListener

150 views Asked by At

I have an ASP.NET 5 app using RavenDB, and I'm trying to create an attribute that will create a "Changeset" document with the keys of all the documents that were stored by the action.

For that purpose, I created an ActionFilterAttribute instantiated via ServiceFilterAttribute, which is registered as Scoped, that sets a flag on another Scoped component, let's call it ChangesetAccessor, which holds the list of changes.

The IDocumentStore is obviously a Singleton, and the listener (IDocumentStoreListener implementation) is manually instantiated. It needs access to the current ChangesetAccessor, so I thought giving it a reference to the IServiceProvider so it can call GetService<ChangesetAccessor> as needed would be enough, but it is receiving a different instance.

How can I get the ChangesetAccessor for the "current request" from my listener?

1

There are 1 answers

0
Matt DeKrey On BEST ANSWER

You can actually access RequestServices off of the HttpContext to get scoped instances. It's kind of backwards, and really will depend on Microsoft.AspNet to do it, but it will work for your situation; interestingly, IHttpContextAccessor is a singleton, too, though it gives you a scoped value.

// injected:
IHttpContextAccessor httpContextAccessor;

// in your method:
httpContextAccessor.HttpContext.RequestServices.GetService<ChangesetAccessor>()