Singleton DataStore on Background Thread - objective-c

I have created a singleton class that accesses a datastore and returns an object representing a Core Data entity. This is fine in the normal thread but I am concerned about accessing this singleton method from another class running on a background thread as the background thread will be running with its own copy of the Managed Object Context.
When trying to call the singleton from the background thread do I need to create a fresh instance of the singleton and pass in the background thread's copy of the managed object context or can I safely access the singleton method and allow that to use the shared managed object context that it retrieves internally from the app delegate please?

Have your data manager class make all the relevant Core Data calls with performBlock: or performBlock:andWait:
That way the calls will always be made in a thread safe manner.
Personally, however, I usually write my data manager so that It is called on the main thread, and it takes care of making any further calls on whatever thread makes sense.

Related

How to share a util object which is not thread safe in light-4j handler

I have generated code from an openapi yaml file. I'm implementing the handleRequest methods. I need to share the same instance of a "Util" object to reuse it in all the handleRequest calls. Could you please tell me where to store my Util object instance?
My Util class is not thread safe, so I should have one instance for each client thread.
If your class is thread safe, the best place is https://www.networknt.com/concern/service/
If the object is not thread safe then save one object per thread with ThreadLocal. That means one request might be calling two or more instance of util objects when a request is dispatched from an IO thread to a worker thread.
If it's actually a util object can you make it stateless so that it is thread safe? Maybe add an additional context type object for the state if you really need it. Attaching it to the exchange as an attachment could work.

Ninject: What happens to non-disposable InRequestScope and InTransientScope objects after the HTTP request is finished?

I have searched a lot about these question, here and a lot of other places, but not getting everything I want to know!
From a WebApi project point-of-view, when are InTransientScope objects Created? In the Ninject docs it is stated that such objects are created whenever requested, but in a web api project that handles HTTP requests, the instance is created at the request start time so in this regard it is the same as InRequestScope then?
In a WebApi project, is it okay to use InTransientScope objects knowing that they will never be kept track of by Ninject? If Ninject never keeps track of Transient objects, then what is the purpose of this scope and what happens to such objects after they have been used?
If I declare an object with InRequestScope and that object doesn't implement the IDisposable interface, what happens to such object after the web request has completed? Will it be treated the same way as an InTransientScope object?
Are different scopes to be used for: WebApi controllers, Repositories(that use a InRequestScope Session that is created separately) and Application services?
There's two purposes for scopes:
Only allow one object to be created per scope
(optionally) dispose of the object once the scope ends.
As said, the disposal is optional. If it doesn't implement the IDisposable interface it's not being disposed. There's plenty of usecases for that.
The InTransientScope is the default scope - the one being used if you don't specify another one. It means that every time a type A is requested from the kernel one activation takes place and the result is returned. The activation logic is specified by the binding part that follows immediately after the Bind part (To<...>, ToMethod(...),...).
However, this is not necessarily at the time the web-request starts and the controller is instanciated. For example, you can use factories or service location (p.Ex. ResolutionRoot.Get<Foo>()) to create more objects after the controller has been created. To answer your questions in short:
When: When a request takes place or whenever your code asks for a type from Ninject either directly (IResolutionRoot.Get(..)) or through a factory. As InTransientScope objects are not being tracked they will not be disposed, however, if they are not disposable and the entire request code requests only one IFoo then practically there's is no discernible difference (apart from the slight performance hit due totracking InRequestScope()-ed objects)
As long as you don't need to make sure that instances are shared and/or disposed this is completely fine. After they are not being used anymore, they will get garbage-collected like any object you would new yourself.
When the scope ends ninject will remove the weak reference to the non-IDisposable object. The object itself will not be touched - just like when bound InTransientScope()
That depends on your specific requirements and implementation details. Generally one needs to make sure that long-scoped objects don't depend on short-scoped objects. For example, a Singleton-Service should not depend on a Request-scoped object. As a baserule, everything should be InTransientScope() unless there's a specific reason why it should not be. The reason will dictate what scope to use...

Asp mvc: IControllerFactory.CreateController and threads

I'm implementing a custom IControllerFactory to create my asp.net mvc controllers.
In this factory's CreateController method, I'm relying on the fact that the thread
that creates the controller, is unique; meaning no other Controller is created on that thread before ReleaseController is called.
Now, under heavy load testing, I'm running into issues.
Say that I have created Controllers on threads 1,2,3, it appears that a new
Controller is being created on thread 1, before the first one has called
IControllerFactory.ReleaseController.
Is this an expected behavior?
Each request to the controller is handled on a separate thread, right?
How comes the same thread is being reused for a different request, before IControllerFactory's ReleaseController method is called?
Thanks for your time,
Koen
In this factory's CreateController method, I'm relying on the fact
that the thread that creates the controller, is unique; meaning no
other Controller is created on that thread before ReleaseController is
called.
You absolutely cannot rely on such behavior. There's nothing guaranteeing you that. Things could get even worse if you use asynchronous controllers.
Is this an expected behavior?
Yes.
Each request to the controller is handled on a separate thread, right?
No.
How comes the same thread is being reused for a different request,
before IControllerFactory's ReleaseController method is called?
ASP.NET uses a thread pool to service requests. So for example a thread is drawn from this pool to service the request and later this thread is returned to the pool for reuse. So you could perfectly fine have the same thread execute the controller code for two completely separate requests.
You should absolutely never rely in an ASP.NET application on threads. If you want to store some per-request specific information you should use the HttpContext storage, not threads. Forget about threads in an ASP.NET application if you want to be safe.

Singleton with a delegate: Good idea or bad?

I have created objects that are interfaces to a web service. One typical object would be a "TaskService". When a client uses one of these objects, it invokes one of the service's methods (such as "GetTasks") and the service will asynchronously go off to call the remote web service, and post back the retrieved data via a delegate.
Currently, to use one of these services you have to create it with [[TaskService alloc] init], but I decided it makes more sense to make each service into a singleton object.
Is it common to see singleton objects that hold reference to delegates? My main issue with the design, is that each object, whenever it requires use of a particular service, will have to set itself as the delegate before invoking the service, which doesn't seem quite right to me... What if another object were to set itself as the delegate inbetween you setting yourself as the delegate and invoking the service?
Many thanks in advance!
Regards,
Nick
Imo this is not a good idea for the reason you cited. The Singleton pattern is really for things there are only one of, but it sounds like your app can have need for multiple instances of these services. I think you'd wind up working around this (using an operations queue or some kind of delegate multiplexer) when you really just need to instantiate multiple instances of your service.
When the occasion warrants the use of a Singleton object, I always avoid delegation for the reason you cite. Consumers of a singleton can't know (without some ugly coding) if they're stepping on some other consumer's toes by setting themselves as the one-and-only delegate of the singleton. NSNotifications are a much cleaner tool for the job; any arbitrary number of listeners can consume the notifications without caring who else may be listening.
Delegation works best when there is clear ownership between the classes. Nobody owns a singleton.
Singleton isn't really the problem, you cause the same sort of issues by simply instancing a class and passing it about as a global variable.
As other's have mentioned a queue is a possibility, or when you invoke a task on a service in your Singleton have it instance a TaskRequest object passing in the method and the call back delegate, that way requests can't trample on each other. In fact it would be a good idea to do that with a queue anyway.
The scope of a singleton is entire application. For example: Let consider the example of shopping application the logger data, about the user ID which need to be accessible on different part of application like order, payment, cart etc.
Delegates are used for 1 to 1 communication, for example: You can take as example You have two classes TV and remote control device. You want to change the channel of TV. Delegate methods of TV for changing channel are implemented in remote control device class. So you use remote control device and you change the channel of the TV.
The singleton is used to communicate with multiple receivers, while the delegation pattern is used usually for 1 to 1 communication.

WCF, Unity: Teardown disposable instances

we've set up a WCF service which uses a Unity Container to resolve instances for managing Exchange 2010 Powershell commands. We defined an IExchangePowershell interface which has a concrete implementation that implements IDisposable. After some time we encountered the problem that we couldnt execute powershell commands anymore since the server said there are already too many powershell sessions open. It seems that we never really disposed of our powershell instances. The Dispose() method of the concrete Powershell would take care of closing the runspace and the session. Once I call this in the repository methods, we don't get the errors anymore.
((IDisposable)this.powershell).Dispose();
Now of course I dont want to explicitly call dispose in every repository method. I thought unity could take care of this. Our WCF Instance Provider does this:
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
container.Teardown(instance);
}
But that doesnt really dispose of the IExchangePowershell instances. Do you have any idea how I could automatically dispose of those instances?
That is actually well known problem in Unity. TearDown method does nothing. If you want to use TearDown you must create custom container extension.
I wrote an article about using object lifetimes managers in Unity and their impact on disposing. If you use default TransientLifetimeManager or PerResolveLifetimeManager the Unity will even don't track existence of your objects so it can't call Dispose. The only lifetime managers which calls Dispose on resolved instances are ContainerControlledLifetimeManager (aka singleton) and HierarchicalLifetimeManager. The Dispose is called when the lifetime manager is disposed.
The solution for you is either use casting and handle Dispose manually as you already did or switch to HiearchicalLifetimeManager and create new subcontainer for each incoming WCF request. Each subcontainer will only handle single request and it will dispose resolved entities with hiearchical lifetime.
There are other ways, for example this article builds a very complex code around Unity to support disposing and TearDown for all resolved objects.
The answer depends on how you register your type / instance with unity. Standard implementation of Teardown does nothing at all.
If you register type then Unity does not store reference to instance it creates - it's up to you to manage it's lifetime and dispose it. If you register instance, then the instance lifetime is managed by unity and is kept until you dispose of the container.
The link below helps to understand a bit better about lifetime management:
http://msdn.microsoft.com/en-us/library/ff648098.aspx
You need to ask yourself when you would like your objects to be disposed. If you know when to call ReleaseInstance, you might as well call IDispose instead of it.
(I'm sorry, I'm not familiar with WCF, so I'm not sure what instance provide is in this context)