Asp Web Api Lifecycle issue - asp.net-web-api

Im using web api 2
I have an authentication filter (implementing IAuthenticationFilter) that checks a token and sets a ClaimsPrinciple on both the Thread and the HttpContext. One such claim is the userId
I am using Windsor for Dependency Injection using the method described here.
http://blog.ploeh.dk/2012/10/03/DependencyInjectioninASP.NETWebAPIwithCastleWindsor/
This will create the object graph for my controllers and therefore new up any dependencies that the controllers have
The problem is that one of the constructors in one of the dependency's makes a call that requires the userid
And it seems that this (the constructor call) occurs before it has been set by the authentication filter
What are my options here?

When Web API needs a controller, the dependency injection is used to create it. This always happens before executing the pipeline. So you cannot access to the userid which is set later.
There are at least these solutions.
resolve the dependency when needed (i.e. use the DI container as service locator). I don't like this one
lazy initialize the dependency (I don't know if Castle Windsor can do it, but it looks like it's possible: Lazy Loading using Windsor Castle) Not so bad
change the implementacion of that component, and receive the userid as parameter, where needed, so that it's available when you want to use it. I prefer this one

Related

Spring Beans Dependency Inyection with different configurations

I have the following doubt, probably a very basic one, that I have already managed to work out but I would like to listen if there is a different approach or actually if I am getting something wrong.
Background
I have an implementation with Springboot with a classic layered approach using Spring StereoTypes and wiring all up using Field DI (yes... I am aware it is not the best approach)
Service -> Repository -> (Something else)
In my case (something else) is a third party Rest API which I am calling using a RestTemplate with a specific configuration.The current solution has many services and repositories to deal with each of the Third Party domain entities. All of them using the same RestTemplate bean. The bean is inyected at the repository level.
Problem
So now I have been told from the Third Party System that depending on which business scenario my local services are executing, repositories need to use one of two different users, therefore, I assume that a different restTemplate config needs to be added. At first glance it drives me to move even higher the decision of which restTemplate to use. At Service level, not at the repo level. So I would need to have, lets say, a service A under a specific context whose dependencies (the repository) will need to have a specific template, and the same service A given another context, with a different dependency config.
Approach
The approach that I took is to have a configuration class where I generate different versions of the same service with different dependencies, in particular, their repositories using a specific template. Github Example
This approach seems like odd to me because up till now I have never had to do something like this ...and leaves me with the doubt if something different can be done to achive the same.
Another approach would be to inject both RestTemplates in the base repository and with an extra parameter to decide which to use in each method that it is being use at service level and repo level. Which I dislike.

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.

Using ServiceLocatorFactoryBean of Spring

I am creating third part login system for my web application using Oauth2 and have to support various third party Oauth2.0 service provider like
Gmail
Facebook
MSN
Yahoo
Twitter
I have already working code for these.Each service provider have a certain set of configuration which need to be created before starting Oauth process.I was thinking about using ServiceLocatorFactoryBean of Spring and create few services for each Oauth provider and based on what user has selected can fetch that specific service.
Is my approach is good enough or is it like a overuse / overcomplicated one
Edit
As per one answer, We can create a single bean with singleton scope and inject Map of required services to it so as we can fetch services from Map based on what user has selected, though approach is fine but won't that force us to load every services in Memory and no matter if we will use them or not, they will remain in Memory
Using ServiceLocatorFactoryBean is a way to do it and solves the problem of getting a bean (implementing an interface) based on a String key lookup.
The javadoc says that the class is meant mostly for injecting prototype scoped beans, but also works for other scopes altough they don't advise it.
The javadoc gives an indication that is not the use case for which the ServiceLocatorFactoryBean was created, another solution that gives the same work is to just create a singleton bean OAuthServiceProvider that returns the correct service depending on a string using just some if/elses or a map.
In the long run it would more readable, the use of the ServiceLocatorFactoryBean seems not to buy us much compared to that.

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.

Asp.net mvc 3 dependency injection

I'm a bit confused with DI and IoC. I have set up MVC and I use Ninject for properties injection and it works perfectly. My application is set to use Portable Areas from MvcContrib and each area is contained from providers, services, models and controllers.
Providers from one area can access other providers in same or sub assemblies. To resolve dependency in provider I use DependencyResolver.Cur... which is registered to use Ninject as well. I would like to know if this is a good approach since I don't want to pass all other providers from controllers to last layer, but I want to access them directly from provider. Should I create an instance of kernel in lowest assembly like Core so I can access it directly from anywhere?
Thnx in advance
UPDATE:
I would also want to know if it is possible to use property injection in normal class.
When you design all your services (reposities, application services, controllers, etc) around the constructor injection pattern, there is no need to call DependencyResolver.Current.GetService from within a class and there is no need to make an instance of the kernel available in the lowest assembly.
When all your services use constructor injection, your container will be able to construct an object graph of dependent services when a root type is requested: in your case a controller class. When you do this, no code needs to access the DependencyResolver or the Kernel directly, which ensures your code will be more testable, flexible, and maintainable. Any code that accesses the DependencyResolver or static Kernel instance is hard to test, hides its dependencies, and makes it difficult to verify the container's configuration in an automated fashion.
Instead of using constructor injection, you can achieve the same with property injection. However, since the convention is that properties are for optional dependencies, Ninject (and any other container) will skip a property it can't inject (implicit property injection), instead of throwing an exception, as would happen with a missing constructor argument dependency. This again makes it much harder to find configuration errors in your application. So, whenever possible, stick with constructor injection.

Resources