How to bind Factory into current request scope? - jersey-2.0

How do I dynamically bind a new Factory into the current request scope? I want the binding to get removed automatically at the end of the current HTTP request.

The provide method of the Factory can be annotated with #RequestScope and then the thing provided by the factory will be in the RequestScope (and hence the factory provide method should get called every time the RequestScope changes).
Is this what you are asking?
It also depends on how you are binding it. Are you using one of the automatic analyzers of the class, or are you using a bind API?
Even the Factory itself (not the provide method) can be in the RequestScope, in which case a new instance of the Factory implementation will get created whenever the RequestScope changes

Related

Autofac Delegate Factories - How to create a new instance each time?

Question: How do I use the Autofac Factory delegate to create a new instance while within an existing Autofac Lifetime scope?
According to Autofac documentation,
If you register an object as InstancePerDependency() and call the
delegate factory multiple times, you’ll get a new instance each time.
This is not true when injecting the factory into the constructor of a class within an existing lifetime scope
Some additional background: I'm attempting to use Autofac Delegate Factories in order to create a new instance of a ValueObject class each time.
This ValueObject class's constructor and delegate factory look like this:
public SlaInMinutes(int slaInMinutes, ISlaCalculator slaCalculator, ITicketUnitOfWork ticketUnitOfWork)
public delegate SlaInMinutes Factory(int slaInMinutes);
Autofac registration looks like this:
builder.RegisterType<SlaInMinutes>().InstancePerLifetimeScope();
When I inject the Factory delegate into a class constructor (SlaInMinutes.Factory slaFactory) within an existing LifetimeScope I am able to instantiate a new class using the Factory parameter, and Autofac takes care of the remaining constructor dependencies. It's great.
Except it's the same instance every time after I instantiate it once. I need to have an new instance each time I call this Factory delegate based on the Factory parameter int slaInMinutes.
Switching my registration from InstancePerLifetimeScope to InstancePerDependency:
builder.RegisterType<SlaInMinutes>().InstancePerDependency()
does not have the effect of creating a new instance each time I call the Factory method.
What I need:
slaFactory.Invoke(1) //new instance
slaFactory.Invoke(2) //new instance
slaFactory.Invoke(1) //same instance or new instance, don't care
This is an ASP.NET Core 1.0 web app, and the Lifetime scope is started during the beginning of an API endpoint call, and it lasts until that API call is completed.
Remove InstancePerDependency/InstancePerDependency method call from your registration if you want to create new instance for each call.
You can refer to the link https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html?highlight=InstancePerDependency for more details regarding instance scope.

How inject dependency in custom TelemetryInitializer?

We are using Autofac 4 for DI and I started experimenting with AI a short while ago. Now I created a IdentityTelemetryInitializer class which needs and IIdentityProvider to be able to get the ID of the current authorized user and set it add it to the context. I cannot find a way in which to inject dependencies into a TelemetryInitializer. If I define a contructor that takes an IIdentityProvider, the custom initializer is skipped altogether.
Any ideas are welcome. I was thinking of having the user ID also set as the Thread Principal so that we can access it this way, but I was hoping I could use DI for this?
You cannot inject dependencies using a constructor as the initializer initialized internally using the default (empty) constructor. When you explicitly defined a new ctor you've actually 'removed' the default one, thus the initializer was skipped altogether, as you've mentioned.
Therefore, the only way is to resolve the dependencies during the 'Initialize' method, after registering them on application startup.
ctx.RegisterType<MyService>().As<IService>().AsSelf(); // on application startup
ctx.Resolve<IService>(); // during initializer 'Initialize' method
You might look at the question I asked here
How to have "Request" events with authenticated user id ?
because I had managed to have the TelemetryInitializer working, passing user id via the HttpContext as suggested by #yonisha.
Off course it's not as lean as what you try to achieve.
The Telemetry Initializer is called each time you instanciate a Telemetry class, so really depending of how you manage them. Btw I am looking for good advice/best pratice on that : for the moment I have one private instance on each Controller that need to track something, but that does not smell good due to lifetime of Controller.

How to make the result from a request factory call available for for injection using GIN?

I have a proxy, let's call it ConfigParametersProxy.
It has a method (for example) String getParameter1();
It is a request factory managed value proxy.
I want to be able to do this with it in my java/gwt code...
#Inject
ConfigParameterProxy parameters;
How do I set this up so this works?
I am using GIN, so have a client module etc.

How do I register a binding with both delayed instantiation and as a singleton

I am new to scaldi. I have a class being used in my cloud environment configuration where I want two things to happen.
bind [EnvironmentInfo] to new EnvironmentInfo initWith(_.init())
First, I want it to be a singleton. It retrieves the runtime information (Google AppEngine in this case) and it should do this once on instantiation. It seems like initWith is a good choice.
Next, I want instantiation to be delayed until first request. Following the execution path it is being instantiated well before the first call.
If I can get delayed instantiation, then initWith should move to the class constructor.
My answer ended up being simple. I abstracted the singleton "state" and accessed it as a 'lazy val ...'.

WebAPI/Unity Intercept Request and Change ConectionString Unity Container for EF Context

I'm building an API that needs to connect to a different database per request. Currently I'm using EF. These databases all have the same schema, therefore I can share a DbContext class. I have repositories to abstract persistence, and these are the ones using the DbContext objects.
Unity is handling dependency resolution, it is injecting my repositories with DbContext objects, and the repos on the controllers. Basically with zero configuration. I understand that probably I may need to create my own HttpRequestLifeCycle thing as suggested in this answer to make sure I have the same DbContext object through out the request.
Now, I would like to configure a ConnectionString to be used by Unity when creating DbContext objects to pass along to the repositories.
These ConnectionString will come from a repository (most likely a different fixed database), based on a parameter on my route. So, my intention is to have a delegating handler inspect the route, get the parameter, get the ConnectionString and tell Unity: "here, use this particular connection string when creating DbContext objects for my repositories during this request."
First, is my approach reasonable? Is this achievable?
How would this dynamic parameter configuration done?
Thanks in advance,
Yes, this is reasonable and achievable and frankly, easy.
Just approach this differently, instead of thinking how to inject connection strings, just register a factory for your db contexts. In the factory method, use the route information to read the connection string and return the context.
containe.Register<MyDbContext>( new InjectionFactory(
c => {
// this is the factory method
// the code will be executed upon each resolution
String routeInfo = GetTenantFromCurrentRoute();
String cs = GetCsFor( routeInfo );
return new MyDbContext( cs );
}, new PerHttpRequestLifetimeManager() )