SimpleInjector RegisterWebApiRequest vs RegisterPerWebRequest - asp.net-web-api

The latest version of SimpleInjector introduced a distinction between MVC and WebApi. Are the two request registrations aliases for the same thing? Or is there underlying differences as well?
Thanks

The lifestyles and scope implementations WebRequest and WebApiRequest in SimpleInjector 2.5 are based on different technologies.
WebApiRequestLifestyle is derived from ExecutionContextScopeLifestyle which works well both inside and outside of IIS. I.e. it can function in a self-hosted WebAPI project where there is no HttpContext.Current. The scope used by WebApiRequestLifestyle is ExecutionContextScope. As the name implies an ExecutionContextScope registers itself in the logical call context and flows with async operations across threads (e.g. a continuation after await on a different thread still has access to the scope regardless of whether ConfigureAwait() was used with true or false).
In contrast, an instance of WebRequestLifestyle is stored within the HttpContext. The HttpContext can be used with WebAPI when it is hosted in IIS but care must be taken because it will not always flow with the execution context because the current HttpContext is stored in the IllogicalCallContext (see Understanding SynchronizationContext in ASP.NET). If you use await with ConfigureAwait(false) the continuation may lose track of the original HttpContext whenever the async-op does not execute synchronously. A direct effect of this is that it would no longer be possible to resolve the instance of a previously created service with WebRequestLifestyle from the container (e.g. in a factory that has access to the container) - and an exception would be thrown because HttpContext.Current would be null.
I would recommend you use WebApiRequestLifestyle for services that should be 'per Web API request', the most obvious example being services that are injected into WebAPI controllers. WebApiRequestLifestyle offers the following benefits:
the WebAPI controller can be used outside of IIS (e.g. in a self-hosted project)
the WebAPI controller can execute free-threaded (or multi-threaded) async methods because it is not limited to the ASP.net SynchronizationContext.
Check out the blog entry of Stephen Toub regarding the difference between ExecutionContext and SynchronizationContext.

Related

EF Core 2.1.1 DbContextPooling in .Net Framework 4.7.2 application

I can find a lot of articles on how to enable DbContextPooling in ASP Net Core through AddDbContextPool function.
But what about .Net framework 4.7.2 when this is not available. How can I reuse the DbContext from the pool?
Thanks
AddDbContextPool sets up services in the dependency injection container to make it more efficient to get DbContext instances for each request.
If you are not using ASP.NET Core, but your application follows a similar model (e.g. DbContext instances are needed to process Web or service requests) and the number of requests per second is very large, then my first recommendation would be to setup DI using Microsoft.Extensions.DependencyInjection and create DI scopes per request like ASP.NET Core does. Once you do that, you should be able to call AddDbContextPool the same way you would do in an ASP.NET Core application, and resolve your DbContext using DI with all the benefits of DbContext pooling.
Besides that option, in theory you could do manually what AddDbContextPool achieves using DI.
For example, first create a singleton pool of type DbContextPool. Then, for every instance of YourDbContext you need, get a lease using pool.Lease, and then get the context using lease.Context.
You have to make sure that you dispose both the context and the lease when you are done using them.
Caveat: this approach requires direct usage of low level APIs that are in internal namespaces and that therefore could change or disappear in any future minor or major release of EF Core.
If your application doesn't work like that (for example, if it is not a web application or a web service that need to process large numbers of requests), then there is no advantage on using DbContext pooling.

Using correctly the #Scope annotation is Spring 3 web application

I recently readed carefully about the spring mvc 3 beans scope, specifically the web ones(session, request and global session) and i have some doubdts:
If i have a controller, why should i annotate him with other scope aside of singleton? I mean, the controllers are supossed to handle the requests and instantiate the view resources of all the app, so why give them a, for instance, session scope? what is the advantage of do that?
Is advisable making the services layer session scoped?
And finally, is there any convention or good practices that dictates where and when is more convenient the use each one of the web scopes? If there is, can somebody provides me the link or information about it? Not necessary convention or good practices, also your experience about it.
Thanks very much.
I mean, the controllers are supossed to handle the requests and
instantiate the view resources of all the app, so why give them a, for
instance, session scope?
In an average web application, you have various objects that exist on a per-session basis. Example can be user profile, or some kind of cabinet, or wallet, etc.
To be able to use those objects in service, every time you should get from session, and pass through the service chain. Instead of doing this, of course it is better to have those available in your service, without a need to pass it explicitly.
Really good example (in practice) you can find here.
An ideal practical example of request scope bean is HttpServletRequest, which should be unique obviously for each request, therefore it is request scoped and created for each request.
From my experience, without any explicit need for a case, you don't need to bother yourself with changing scopes. It is not without reason that default scope is Singleton, it is by purpose - because in most of the applications and basic scenarios you need beans as singleton. However as your main concern was with Session and Request scopes, the above examples are cases which you need often in web application.

Single instance of an object per transaction

I have a use case, that theoretically seems to me as it would be a solved problem. But i'm not able to find a sure fired implementation.
I've created a RESTful API, using Apache CXF, Spring and Hibernate
This application encompasses a standard Service-Proxy-DAO layered structure
I need to instantiate a custom logger object at my service (or pre-service) layer and initialize a bunch of parameters which will remain constant, for the most part through every call that goes through my application layers and back.
How can i, for every individual service call, initialize this logger object once, and use it across all my layers without having to instantiate it everytime. Either i inject the initialized object in every class i need or something on those lines.
I don't want to use static blocks, or pass the object in method signatures.
Is there anything that i can use as a part of the Spring, CXF or other java framework that allows me to implement this use-case.
EDIT: I would define a transaction as a single call to a web service endpoint, from invocation to response.
ThreadLocal would be an ideal candidate to solve your problem.
UPDATE:
Creating a thread local that is available in all the places where this "shared" reference is required will give all these contexts access to this resource without having to pass the reference around.
see http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/ - looks like a good explanation of how to use thread local and also deals with your problem space.

Per-Request DependencyResolver in Web API

In MVC, a ModelValidatorProvider is instantiated and called to validate a model on each request. This means that in a DI environment, it can take dependencies on objects scoped within a single request, such as a Unit of Work or Database context. In Web API, this appears to have been significantly changed. Instead of being instantiated per-request, the ModelValidatorProvider appears to be long-lived and instantiated within the application startup. The WebAPI then caches the results from the ModelValidatorProvider per-type, meaning that the ModelValidator cannot take any dependencies from DI.
I am trying to implement my ModelValidator to use a factory using a Service Locator (please, no automatic 'anti-pattern' comments!). This would allow me to construct an internal validator object within each request, which would be able to take dependencies from the container. However, I cannot get hold of a Dependency Resolver or container scoped to the current request from within this ModelValidator which is essentially scoped as a Singleton. I've tried to use GlobalConfiguration.Configuration.DependencyResolver, but this only returns globally-scoped services (from the root scope, also mentioned here)
I'm working in Autofac, so an autofac-specific solution would be suitable (e.g. MVC has AutofacDependencyResolver.Current, which internally uses DependencyResolver.GetService). There is no equivalent available in the WebAPI integration, presumably because of the reason mentioned above where the global DependencyResolver only returns globally-scoped services.
The reason I'm trying to do this (as well as for my own use) is to implement the Web API integration for FluentValidation, which currently does not exist. There have been two attempts so far, but neither of these handle the Dependency Injection issue and instead result in a single static ModelValidator.
Things I've tried so far:
Using GlobalConfiguration.Configuration.DependencyResolver (returns objects from the root scope)
Taking a dependency on Func<IComponentContext> (always returns the root context)
In an answer which has since been removed, it was suggested to remove IModelValidatorProvider service from the Web API config. This had to be done using reflection since the interface and the implementing classes are all defined as internal, but it did make the validators work better (because the ModelValidator was constructed per request). However, there is a significant performance hit to doing it this way due to the use of reflection to check for validators on the model and every property it has, so I don't want to take this option.
Filip W's answer suggests using HttpRequestMessage to get the Dependency Scope, but I've not found anything such as HttpRequestMessage.Current which would provide access to this object from within a long-lived object - if that could be achieved I believe everything would fall into place.
To get current dependency scope, you have to use (surprise, surprise :) GetDependencyScope() of the current HttpRequestMessage (more about which you can read up on MSDN) instead of GlobalConfiguration.
I blogged about Web API per-request dependency scope a while ago - that should be helpful.

Application_End() WebApi

In ASP.NET WebAPI there is a method called ApplicationStart in the global.asax.cs file which is automagically called when the application started. How is this called?
The reason I ask is I would like to add an Application_End method to do any cleanup I need to do.
ASP.NET WebApi is no different than ASP.NET when it comes to the Global.asax methods. These methods are discovered via reflection by the IIS application pool worker when the application is loaded and are then invoked at the appropriate times. There is a nice overview of this on MSDN, particularly the Global.asax methods like Application_Start() and Application_End().
Application_Start() is called by IIS when the application starts running inside the application pool. Generally, this happens when a request comes in for a resource within the application's domain. After all, the application has to be running for the request to be serviced.
Application_End() is called just before the application is unloaded or just before the application pool recycles. There are various triggers that cause the application pool to recycle.
MSDN has the full details here - http://msdn.microsoft.com/en-us/library/ms178473(v=vs.100).aspx, but the key bit that your interested in is:
Application_Start ..... Called when the first resource (such as a page) in an ASP.NET application is requested. The Application_Start method is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.
Essentially it is invoked once per application life-cycle automatically by the application container (e.g. IIS).

Resources