Dependency Injection creating new object everytime an api is called - node.js

Everytime I'm calling an api in inversify-express server the dependency is creating a new object everytime
var kernel=new Kernel();
kernel.bind<interfaces.Controller>(TYPE.Controller).to(SyncController).whenTargetNamed(TAGS.SyncController);
kernel.bind<DB_SyncDataDAO>(TYPES.DB_SyncDataDAO).to(DB_SyncDataDAO_Impl);
kernel.bind<SyncService>(TYPES.SyncService).to(SyncService_Impl);
Whenever I'm calling an api it is creating new object of each dependency everytime

I assume that you want some of the dependencies in your object graph to be singletons. You can do that using inSingletonScope when declaring a binding:
kernel.bind<interfaces.Controller>(TYPE.Controller)
.to(SyncController)
.whenTargetNamed(TAGS.SyncController)
.inSingletonScope();
kernel.bind<DB_SyncDataDAO>(TYPES.DB_SyncDataDAO)
.to(DB_SyncDataDAO_Impl)
.inSingletonScope();
kernel.bind<SyncService>(TYPES.SyncService)
.to(SyncService_Impl)
.inSingletonScope();
As a side note (not related to your question) if DB_SyncDataDAO_Impl is an instance (nota class) then you should use
kernel.bind<T>("T").toConstantValue(instanceOfT)
Instead of:
kernel.bind<T>("T").to(classWhichIsAnImplementationOfT)
When you use toConstantValue, inSingletonScope is not required because constant values behave as singletons by default.
Hope it helps :)

Related

Why TypeOrm advises to create empty object via `new EntityClass()` THEN only pass fields value?

I'm using NestJS (not Next) NodeJS framework
When I'm creating new objects I used to use new OjbectClass({...fieldsValues});
It's great especially when you use transform pipes from class-transformer;
Besides this approach is used for entity creating:
https://docs.nestjs.com/techniques/database#separating-entity-definition
But as far I see in different guides of TypeOrm usage
here: https://typeorm.io/#/ ,
and here: https://orkhan.gitbook.io/typeorm/docs/entities .
They show first to create an empty object, then only set fields with values:
const object = new EntityObject();
object.field = 'value';
Why? Does it make sense?
Does NodeJS create a redundant hidden class of properties passed via object into Entity Class constructor? If yes - then we can pass coma-separated arguments
I believe it's just cause that's how the docs are. Looking at the code for BaseEntity it does not look like having a constructor to assign the fields would be a problem

AutoMapper inline mapping throwing mapper not initialized

I'm trying to use AutoMapper in a API wrapper class library project to map from API models to our domain models. While looking at the AutoMapper documentation I ran into the inline mapping feature.
Documentation says:
AutoMapper creates type maps on the fly (new in 6.2.0). When you call Mapper.Map for the first time, AutoMapper will create the type map configuration and compile the mapping plan. Subsequent mapping calls will use the compiled map.
So I wrote the following line of code in my wrapper class library:
var data = response.Results.Select(Mapper.Map<Session, Media>).ToList();
basically just trying to map the Session object I get from the API into our Media objects. But this throws the following error:
Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.
I was under the impression that inline mapping is exactly supposed to bypass having to initialize and define configuration for AutoMapper? Am I wrong?
Also if I am indeed wrong then how are you supposed to configure and initialize AutoMapper inside a class library to where it happens only once? I would like the library to be independent, meaning I don't want the programmer using the library to have to configure AutoMapper in his project in order for the library to work properly.

Different Java objects having the same address, IsSameObject not working, and related global ref management problems

I've been banging my head on this problem for a week, and now I'm starting to understand what's going on, but no idea why, or how to fix it.
Let me describe what I'm doing. I have an assortment of various objects in Java, and I have a native library. Java objects inform the library of their existence by calling NativeLibrary.AddObject(this). The native library has a container of jobjects where I store global references to the Java objects, obtained with env->NewGlobalRef(object). The native library uses these stored references to access the Java objects, and it does work fine.
And here's the crucial part that does NOT work. Obviously, I want to be able to delete Java objects, not only add them. So, when a Java object is no longer needed, it calls NativeLibrary.RemoveObject(this). The native library implements it by iterating the list of stored objects (which are all global references, as you may remember) and finding a match with env->IsSameObject(passedObject, storedObjectGlobalReference).
And here's where the problem is: it doesn't work as expected, the Java objects are not matched to their global references properly. When I started digging and logging all the calls with all the parameters, I noticed a weird thing: the jobject parameter of the native call (which is this of Java objects) has the same value for different objects! Moreover, this value changes between the ``NativeLibrary.AddObject(this)andNativeLibrary.RemoveObject(this)` calls for the same object!
So, what's going on, and how can I store, keep track of and delete the references to Java objects in native code? To reiterate: everything works fine as long as I only create and store global refs; the correct objects receive notifications via these refs, no problem. But as soon as I try deleting these references via env->DeleteGlobalRef, I find out that in the NativeLibrary.RemoveObject(this) implementation fails to match the stored reference to the passed jobject.
I was with the same problem. The root cause was that the added item NativeLibrary.AddObject(this) not was the same object when I called NativeLibrary.RemoveObject(this). I was using junit and this was causing the problem, because junit create multiples objects to run each test. I found the problem using System.out.println with the object in Java side. Before add function System.out.println("add object: " + sameObject); and before remove function System.out.println("remove object: " + sameObject);. Sorry for poor english, I hope this help someone.

Should an instance of a JsonServiceClient be wrapped into a using statement?

Is it a best practice to wrap the ServiceStack's JsonServiceClient within a using statement?
var client = new JsonServiceClient();
client.Post(request);
versus
using (var client = new JsonServiceClient())
{
client.Post(request);
}
Which one is the best?
JsonServiceClient implements IDisposable so best practise would be to use it with a using statement.
However there are scenarios whereby you need to the share an instance of the JsonServiceClient across multiple requests (Such as when you use cookie based sessions, as the cookies are contained in the instances cookie container), in which case you would use the client without a using statement, but ensure that your application calls the Dispose method of the client, when it no longer requires the client.
This answer by gdoron further explains the best practise regarding classes that implement IDisposable such as the JsonServiceClient and the reasoning behind it.
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):
I hope that helps.

Kohana helper attribute

I have a question that keeps bothering me. Currently, I have started using Kohana 3.2 Framework. I've written a helper to handle some functionality - I have a number of methods, which are (as it should be) declared STATIC. But, all of these methods are somehow working with the database, so I need to load a model. Currently, every method has a non-static variable like this:
$comment = new Model_Comments;
$comment->addComment("abc");
OK, it seems to be working, but then I wanted to get rid of this redundancy by using class attribute to hold the instance of the model (with is class as well).
Something like this:
private static $comment; // Declaring attribute
self::$comment = new Model_Comment; // This is done within helper __constuct method
self::$comment->addComment("abc"); // And call it within the method.
But, I got failed with: Call to a member function addComment() on a non-object
Question is: is it possible to do it ? Maybe there are some other approaches ?
Sorry for a long story and, thanks in advice! :P
A static method cannot call a non-static method without operating on an instance of the class. So, what you're proposing won't work. There may be a way do accomplish something similar, but what about trying the following:
You could implement the singleton or factory pattern for your "helper" class. Then, you could create the model (as an attribute) as you instantiate/return the instance. With an actual instance of your "helper" class, you won't have to worry about the static scope issues.
In other words, you can create a helper-like class as a "normal" class in your application that, upon creation, always has the necessary model available.
I'd be happy to help further if this approach makes sense.
David

Resources