Symfony 4.1 - Service using EntityManagerInterface produces max nest level error - autowired

I have created a simple service that takes 4 parameters. When adding EntityManagerInterface as parameter I get max nest level error. The same happens even if pass the arguments manually (withought autowiring).
Interestingly enough when I remove the EntityManagerInterface parameter it all works fine. The problem is, I need the EntityManager in the service.
Any ideas where to look at?

For anyone suffering in the future from similar situation the problem was the following
The service that was requesting for EntityManager was getting injected in a doctrine lifecycle class. Apparently this causes an infinite recursion issue as doctrine is not really initialised at that point and it tries to initialise it.
Setting the service as lazy doesn't work as it's required in the constructor. Is there some way around it to keep the EntityManager dependency in the service and still use it in the doctrine lifecycle event class?

Related

InRequestScope is not disposing

I'm using Ninject in an ASP MVC project for database binding. In "private static IKernel CreateKernel()", I'm binding a database object like below:
kernel.Bind<IDbSession>().ToProvider<IDbSession>(new NhDbSessionProvider()).InRequestScope();
This works almost exactly as intended, but some pages on the site use AJAX calls to methods on the controller and it seems like every one of these calls opens a SQL connection and doesn't dispose of it when the controller returns. Eventually this causes the NumberOfConnections on the SQL database to exceed the max and the site throws errors that connections aren't available.
I'm pretty new to Ninject and taking over an existing project trying to make this work without doing major changes. Any ideas what I can do to get these objects to dispose? It seems like they should be automatically doing this already from what I'm reading, but maybe I just don't understand.
If I need to share more code let me know.
Disposable instances are Disposed at end of request processing, according to the documentation.
However, the documentation for InRequestScope has a section on Ensuring Deterministic Dispose calls in a Request Processing cycle.
Specifically:
Use the Ninject.Web.Common package
Manually registering OnePerRequestModule in web.config (e.g. if you're
not using a Ninject.Web.MVC* NuGet Package)
It is perhaps the case that your instances are being/will be Disposed, but just not at the time you're expecting them to be.
Seems someone commented out this line for whatever reason (it wasn't me). Adding it back resolves the problem.
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));

Autofac InstancePerRequest scope - reuse the scope instance to other places

I am using Autofac as a dependency injection container in my project. I would like to make use of InstancePerRequest scope as I don't want those objects to outlive a request.
Below is the code I am using in the gateway class where I know each of my request will pass through it.
using (var scope = _container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var service = scope.Resolve<MyTestService>();
...
}
Now in my code I locate several other classes where I need to resolve the MyTestService which at the moment is causing an exception with a message No scope with a Tag matching 'AutofacWebRequest'. The exception is because I am calling the resolve on a container instance, whereas I should call resolve on the same scope instance, as shown above.
Can someone please help me to know how do I access the same scope instance at those places in my code? I can't keep calling the BeingLifetimeScope in all the classes.
Unfortunately I'm stuck on a phone and my house is being remodeled so I have no computer access. As such you'll get a shorter answer with no code but it should unstick you.
You say you've read the docs, so you should know:
When you create a scope in those using blocks it's not the same as the current request scope.
If your service is used inside an existing request then you should just be injecting what the service needs right into the constructor, not doing service location with a scope.
If your service is not used inside an existing request then you're on your own to figure out how to mimic a request around your service. There's no fixed way to deal with that since it's app specific.
If the whole point in needing a request scope is to get dependencies registered per request to resolve outside a request then you should switch to instance per lifetime scope.
If you must - and it's an anti-pattern, but if you must - you can put a constructor parameter in your service that is an ILifetimeScope. That will get the current scope injected.
It's not really possible from your question to tell why you need the scope. I'm guessing there may be better ways to do what you're trying to do but being stuck on my phone I can't really expand on the million possibilities and ways to work around doing what you say you need to do. In future questions consider explaining more about the context - why your service needs to pass through a "gateway" and why you're in the situation and not just injecting constructor parameters and letting Autofac integration do the heavy lifting.
Regardless, this should get you unstuck. If not, you'll need to clarify your question with additional context and maybe someone else can hop in.

Groovy/Grails, thread safety and closures

I'm investigating what looks like a race condition in my Grails application. I occasionally see what I think can only be the result of 2 different threads interfering with one another when the application is under a lot of load.
The offending code builds a query using a closure (which is defined at class-level, like a method) which dynamically adds query parameters based on the properties of the domain class. On the surface the code looks fine (to me, as a Java developer), however I stumbled across this comment regarding controller scope in the Grails docs (emphasis mine):
prototype (default) - A new controller will be created for each request (recommended for actions as Closure properties)
session - One controller is created for the scope of a user session
singleton - Only one instance of the controller ever exists (recommended for actions as methods)
Reference
So my question is: what are the implications of using a closure (instead of a method) in a service which is a singleton?
EDIT:
The code is part of the grails quick search plugin:
https://github.com/tadodotcom/grails-quick-search/blob/master/grails-app/services/org/grails/plugins/quickSearch/QuickSearchService.groovy
There are 2 closures, aliasBuilder and propertyQueryBuilder which I think may not be thread-safe.
Should you still need a solution, I just happened to fork that plugin and I stumbled upon the same problem (in the same concurrent scenario).
The long story short, helped by this post, I applied the #Synchronized annotation to the search method of QuickSearchService service and the exception (NPE btw) went away.
HTH

how to set datasource properties dynamically

I am using Grails and as my project's requirement I want to connect to databases as per users requirement. So I have to take the DB credentials like username,password,URL from user. How can I connect to their databases by setting these values in datasource at run time. Is there any way that I can set these values dynamically?
I will explain the concept and leave the implementation up to you. Be aware, this isn't exactly simple and does require you to do some research into the details, but if you are willing to do so, you can accomplish this.
The basic concept here is that each data source in your application is defined as a Spring bean. This is the default behavior of any Grails application. As such, you can replace a bean with a newly defined one. In your case you will want to do this with your second data source. The bean name is determined by how you have it named in your DataSources.groovy.
Take a look at the Spring section of the Grails documentation where it shows some examples of configuring a data source. The same concept will apply in your case. Just be sure you use the correct bean name and that you also call the destroy/close method of the existing bean before you replace it.
Depending on how you implement the replacement (and if you use a GenericBeanDefinition or not) you may want to use grailsApplication.mainContext.registerBeanDefinition(beanName, beanDefinition).
As I stated, this can be done, but you are going to have to learn a bit about the internals of Spring and bean definitions, as well as the API to build and manipulate them at run time.
Hope this helps get you started.

Refactoring large application for ObjectFactory.GetInstance to use nested containers

I have a large application which uses the old way of getting instances using ObjectFactory.GetInstance().
Now I want to move to application to the more correct way of injecting dependencies using constructor injection. However, it is almost impossible to convert all code at once (some static classes use ObjectFactory.GetInstance, other services do not have constructors with all dependencies, ...).
I was wondering if there is a way of replacing ObjectFactory.GetInstance calls with an replacement that uses the current nested container, e.g. replacing all ObjectFactory.GetInstance with Ioc.GetCurrentNestedContainer().GetInstance, to get it quickly up an running.
But how would I could I implement Ioc.GetCurrentNestedContainer to return the currently active nested container?
I can not inject IContainer in all these classes (some are static or have no corresponding
constructor), so they can not use constructor injection (yet).
DI is used in MVC, WCF, and Task based scenarios in this application.
Whilst I can't talk about WCF and task based scenarios, I can offer my recommendation for MVC (having spent time looking the options to a similar problem myself.
The solution to I've come across and ultimately settled for after seeing recommendations by StructureMap's creator, is to have a HttpContext bound nested container created on each request and stored within HttpContext.Items. From here you can reference the container by casting the instance stored within HttpContext.Items to an IContainer.
Infact, this is the same solution used within the StructureMap.MVC5 nuget package.
With this solution in mind, there's nothing to stop you replacing the ObjectFactory with with your own factory that returns the nested container from HttpContext.Items.
Update:
If HttpContext isn't available to you then the only other options I'm aware of is to create your own instance of the object factory that creates a new container and stores it in a Lazy<T> as suggested here and on the StructureMap's Google Groups page here.
I was going to suggest possiblity posting this question on the StructureMap Google Groups, but I see you've already done that. As an avid StructureMap user I'm keen to see what other suggestions arise from your post so I will be watching closely.

Resources