In a .NET Core 2 WebAPI app, what is the scope and lifetime of a dbcontext - asp.net-core-2.0

I have a .NET Core 2 WebAPI application. In Startup class' ConfigureServices I add a DbContext with services.AddDbContext<> and a repository with services.AddScoped<,>...
When is the dbcontext created and how long does it last?
I my WPF desktop days I created my dbcontext within a Using statement, so, I always knew the scope. But now the lifetime of the dbcontext is a little less obvious to me in the Core 2 WebAPI. And, multiple users can hit the API at the same time, do each of them get their own dbcontext?

By default, the context is added "scoped" in ASP.NET Core parlance, which means really request-scoped for the most part. Your main application runs just once (everything in Startup, etc.). For each request, a unique request pipeline is created, which involves newing up things like controllers, which will then be disposed at the end of the request. With a request-scoped context, your context, too, will be newed up the first time it needs to be injected in the request pipeline, and all future uses of the at context, within the same request pipeline, will use the same context. At the end of the request, it will be disposed.

Related

Unrecognized Spring cache annotations when self-invoking a method from within the same bean

Dear Spring Cache project community,
currently I'm implementing an Apache CXF-based Spring (version 4.1.5) web service endpoint using the contract 1st approach. Here, I observe when annotating a public method within my web service class, the Spring cache annotations "#Cachable" are ignored each time I call this method in a self-invoked way within the same bean. This could be proven when taking a look on the cache repository (via JMX) of the underlying cache provider (here: EhCache). There, no filling of the cache takes place.
After taking a look on the current Spring documentation below
Enable caching annotations and
The dispatcher servlet I assume it might be due to the fact that:
<cache:annotation-driven/> only looks for #Cacheable/#CachePut/#CacheEvict/#Caching on beans in the same application context it is defined in. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for beans in your controllers, and not your services. See Section 17.2, “The DispatcherServlet” for more information.
Currently, an Apache CXF "CXFServlet" registered within the "web.xml" deployment descriptor is starting a Spring WebApplicationContext using the "cxf-servlet.xml" Spring application context file by default. There, the <cache:annotation-driven/> is located.
Or is it maybe due to the fact that I'm calling the #Cacheable annotated method from within the same Spring bean so that the generated Spring proxy is bypassed? Details can be found in the "Proxy mechanisms" chapter (9.6) of the Spring documentation as well.
But I do not know how to change the behaviour so that my method results are being cached. Do you have any ideas? Or are my assumptions I posted above incorrect?
Dear Spring community,
I found the important comment within the Spring documentation that approves my assumption:
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual caching at runtime even if the invoked method is marked with #Cacheable - considering using the aspectj mode in this case. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. #PostConstruct.
In consequence this means refactoring the code when relying on Spring AOP and its proxy mode technique or switching the mode from "proxy" to "aspectj" <cache:annotation-driven mode="aspectj"/>. This allows using self-invoking methods within the same class as AOP does static respectively dynamic weaving and so manipulates the byte code directly.

ServiceStack service being singleton by default may cause its request context to be corrupted?

My ServiceStack implementation has service implementations that rely on the HTTP cookies / request. Let's assume the following scenario.
On the very first authenticated user request, the ServiceStack AppHost is able to resolve a service, injects it with the user's RequestContext (request, response, cookies etc) and off we go. Let's assume that this request actually takes a while to process.
Note that by default (from the ServiceStack documentation) the service instance actually comes from a singleton.
By default all dependencies registered in Funq have singleton scope, where the same instance is injected into all dependencies.
Consider now a separate request by a second, different user, when the first user request has yet to finish executing. AppHost resolves the service instance again, and injects the second user's RequestContext. Let's also assume that this request takes a while to process.
If by now the first user thread regains control and has to read its RequestContext from the service instance - wouldn't it now be corrupted from the second request?
Understandably I can configure the service instances to be of request-lifetime, but is it correct to assume that by going over the scenario above I may easily run into request context corruption?
The quote in your question relates to manually registered dependencies, which by default are singleton unless you specify otherwise. Auto-wired services are registered in the container as ReuseScope.None.
If you're registering services manually, you should probably use IAppHost.RegisterService(Type serviceType, params string[] atRestPaths) which also registers services as ReuseScope.None.

Can one instance of a ServiceClient be used in multiple threaded application (MVC)

In my ASP.NET MVC controllers, I want to call a servicestack based service (not hosted in MVC site). In order to make the code testable, I want to inject this service client into the contoller constructor.
Assuming I have my own class that inherits from JsonServiceClient, can I use a singleton of that service client for all the MVC calls? This means the client would have to be thread safe.
Either the (Autofac) registration can be a singleton:
builder.RegisterType<SomeServiceClient>().SingleInstance();
or it has to be per http request:
builder.RegisterType<SomeServiceClient>().InstancePerHttpRequest();
Found a blog article where another servicestack user seems to use a singleton, but I was not sure: Blog Article Showing an Example
Each request is generally re-entrant so it's mostly ThreadSafe to use as a Singleton, the one caveat is that it shares the same CookieContainer, whilst the ServiceClients doesn't mutate the CookieContainer Collection itself, the underlying WebRequest would and it's not known whether WebRequest synchronizes access around it - although I've never personally seen any issues with them.
You can disable Cookies being used (i.e. if your client doesn't require a session) with:
client.StoreCookies = false;

Why does ServiceStack's AppHostBase.Configure take a Container parameter?

AppHostBase already contains a Container property (which resolves to EndpointHost.Config.ServiceManager.Container if defined), so why not just use Instance.Container (e.g., for registering dependencies, plugins, etc.) inside Configure or elsewhere inside any AppHost implementations?
I do note that Configure is a public call, so it could technically be called from anywhere, although it appears that AppHostBase.Init() is the only place in the ServiceStack codebase that does so.
All configuration and registration should happen within the context of the AppHost.Configure(Container) method, after which point it should remain immutable (readonly) for ThreadSafety.
The Container is passed in because that's where all the application dependencies should be registered on. The Container property itself should therefore be treated as read only which is why core classes like IAppHost only exposes a IResolver.TryResolve method.

Spring #Controller lifecycle

I am new to Spring MVC and would like to know how it handles requests, more specifically:
I would like to know how a Spring
#Controller's life cycle relates to
that of a Servlet?
I would also like to better
understand what are the best
practices for multi-threaded
enviornments (e.g. like in Servlets,
are class attributes visible to
multiple HTTP requests as objects are
reused from the pool)?
A controller (as any spring bean) has a scope.
At best your controllers should be of scope singleton. In that case it is very much like servlets, and:
they are created only once, during the application context startup (and destroyed when the context is destroyed)
you should not use any instance variables (as this is not thread-safe)
If your controller scope is request or session, then you can have instance variables, and an instance of the controller is created on each new request/session.

Resources