What is the equivalent of MEFs CreationPolicy.NonShared in Ninject - ninject

I know that CreationPolicy.Shared means singleton, as explained in here in this SO question.
So what about NonShared?
Should I have something like this?
Bind<IDataRepositoryFactory>().To<DataRepositoryFactory>().InTransientScope();
Or should I leave it without any scope like
Bind<IDataRepositoryFactory>().To<DataRepositoryFactory>();
What is the difference between the above two?

The default scope in Ninject is Transient, which effectively means a new instance will be created every time one is requested, so there is no difference between your two examples.
More on Ninject scopes here:
Transient - A new instance of the type will be created each time one is requested. This is the default scope if none is specified.
Singleton - Only a single instance of the type will be created, and the same instance will be returned for each subsequent request.
Thread - One instance of the type will be created per thread.
Request - One instance of the type will be created for each Web Request. See the Ninject.Web.Common InRequestScope article for more information before using this.
Named, Call, Parent - Supplied by an extension. See Ninject.Extensions.NamedScope extension for more information before using this.
Custom - You can also easily define your own scopes using the .InScope(Func selectScope) method.

Related

Ninject how to prevent shared objects

I have a binding like the following in my kernel
kernel.Bind<IMyDependency>().To<MyDependencyImplementation>();
In a single app domain, we multiple calls to kernel.Get<IMyDependency>() are made, does Get<> returns a shared instance or a new every time?
We discovered a thread-safety issue in one of our dependencies that teams are working on rectifying, but in the interim if we can get ninject to distribute one separate object (not shared) per Get<> call, it could save the day for us.
Is there any way in Ninject to say for one particular dependency to return a new instance (or at least a non-shared one) with every Get<> Call?
does Get<IMyDependency> returns a shared instance or a new every time?
You get a new instance of MyDependencyImplementation on each call. This is the default behaviour unless the call to Bind() has been made with a specific scope.
You may have a look at the Scopes documentation.

Using selection strategies with a cache in Curator

The page on Service Discovery using apache curator (https://github.com/Netflix/curator/wiki/Service-Discovery) introduces the following concepts:
The main abstraction class is ServiceProvider. It encapsulates the discovery service for a particular named service along with a provider strategy. A provider strategy is a scheme for selecting one instance from a set of instances for a given service. There are three bundled strategies: Round Robin, Random and Sticky (always selects the same one). ServiceProviders are allocated by using a ServiceProviderBuilder.
Each of the above query methods calls ZooKeeper directly. If you need more than occasional querying of services you can use the ServiceCache. It caches in memory the list of instances for a particular service. It uses a Watcher to keep the list up to date. You allocate a ServiceCache via the builder returned by ServiceDiscovery.serviceCacheBuilder().
I can see how to use the Provider strategies with a ServiceProviderBuilder, but there's no equivalent method on the ServiceCacheBuilder, and the only relevant method available on the ServiceCache class itself is getInstances(), which gets all instances.
How can I use a provider strategy with a ServiceCache?
#simonalexander2005 I was just looking in the code and it turns out that ServiceProvider internally already uses a serviceCacheBuilder. TBH - I've either forgotten about this or it got put in by another committer - I'm not sure. Anyway, I'm very sorry about the runaround here. Also, the documentation must be updated to reflect this - I'll open an issue for this today. I'm sure this be maddening to you, again sorry for this. The good news, though, is that with ServiceProvider you automatically get caching.
Frankly, the docs on this are really bad. It would be fantastic if someone could give a pull request with better docs...
Notice that ServiceCache implements InstanceProvider. Also notice that ProviderStrategy.getInstance() has as its argument InstanceProvider. Therefore, you can pass a ServiceCache instance to whichever ProviderStrategy you want to use.
I hope this helps.

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...

Ninject provider can't resolve types registered within a named scope

I am using the NamedScoped Ninject extension in an attempt to create object graphs that are constructed everytime a command handler is constructed by the container. In other words, I want a fresh object graph for every command that might get processed by its corresponding handler.
I have used the .DefinesNamedScope("TopLevelOrhcestrator") binding when registering my "command handlers" as they are the top level for command processing.
A type in this named scope needs to be injected with the result of a method call on a type already registered in this named scope. I thought the best way to do this would be with a ninject provider.
Inside the provider I attempt to resolve the type in hopes I can call a method on it to pass into another object I am creating within this named scope. The problem I'm having is that when I ask the IContext for the instance inside the customer provider I get an exception that says "No matching scopes are available, and the type is declared InNamedScope(TopLevelOrchestrator).
context.Kernel.Get<TypeAlreadyRegisteredInScope>().MethodThatGetsAnotherDependency()
Is it possible to get types from the container inside a Ninject provider when they are registered inside a named scope?
EDIT
I apologize if the use case seems a bit odd, I am experimenting with some ideas about how to manage my units of work and other services/managers that may need a handle to the uow to complete a business usecase. I know its common for the unit of work to be "started" and then passed into all dependencies that may need to take part in a larger process. I was thinking I'd rather let my orchestrator take a unit of work factory so that it could deterministically destroy the UOW and it would be clear who the owner of a usecase is. What would get supplied to the managers/services would be a proxy to the unit of work that would be null until a real unit of work was started by the orchestrator. That's why I was attempting to link the proxy from the already registered type in my provider. This is all very experimental at this point and was testing some ideas.
I'd be happy to hear any further thoughts.
For MethodThatGetsAnotherDependency() to be able to .Get<>() an instance that is bound .InNamedScope(...) you will need to add the Context Preservation Extension.
This is because NamedScope is adding a parameter to the request context of the binding that has .DefinesNamedScope(...). As soon as that request is over, that context and it's parameters are forgotten. Now with the ContextPreservation extension the context is kept and reused for late / factory creations (Func<>, interface factory with .ToFactory() binding...). It think it should also work with providers.
If not, just switch to a factory instead of a provider.
However i have to admit that i don't fully understand why/what you are trying to achieve. There might be simpler ways.

Transient vs per webrequest lifestyle, what constitutes a web request?

What are the differences between these two life cycles?
Let's say my MVC controller is being supplied with an object that was configured as transient, then when someone visits a method in that controller a new instance is injected in the class constructor and then the method is called.
Each and every get/post to the controller is a new request, right? If so, then I don't see any difference between the two.
Can someone explain / provide an example of when you would use one vs the other?
The difference between Transient and Web Request is negligible when registering your Controller types as Transient, since -as you said- each request gets its own Controller and only one controller instance for that type is resolved in that request.
Things start to get interesting when there's a dependency in the Controller's object graph that is refered by multiple components. A good example for when this might happen is with a Unit of Work (such as Entity Framework's DbContext). Multiple services inside the object graph might need that same Unit of Work, and for the correctness of your application they all need the same instance during that request; but each request must get a new Unit of Work instance.
To learn more about when and when not to have one Unit of Work Per Request or not, read this:
One DbContext per web request… why?
You cannot fault your DI tool for failing to distinguish between cases it doesn't know. PerWebRequest scope is a scope that lasts from the beginnning of a webcall to the end of the webcall. Transient lives as long as you hold a reference to the resolved entity (usually the caller's lifetime).
Of course if the resolving entity has the same lifespan as the request you won't see any difference. A PerWebRequest lifespan lives from the beginning of a request to its end. A Transient lifespan lives according to reference held on it; if you need some logging completely dependent on the current webrequest you would set a PerWebRequest lifespan. The controller that handles the request would get a Transient lifespan since its work finished it wouldn't be needed anymore