Reputation: 1455
I understand a lot of the appeal of using dependency injection frameworks such as Ninject / Spring / etc. I love the idea of coding up new classes without having to think about where the dependency is coming from, just that it's given to you somehow.
I find a lot of the examples I've read use singleton classes. So you have something like:
class A
{
Database _db;
A(Database db)
{
_db = db;
}
}
And since there's only one database across the system, you can register the database at the application entry point, with something like:
Bind<Database>().AsSingleton()
What I don't understand is how to approach the situation where your dependencies aren't singletons, and there may be multiple instances of them at any one time. The DI frameworks that I've seen seem to only give you the option of either defining it as a Singleton or having a new instance created for each using class.
Manual dependency injection? Define a factory object that chooses the instance to use? Some kind of heirarchical scoping mechanism to allow you to pretend they are singletons? What kinds of patterns exist for this case?
Upvotes: 2
Views: 1114
Reputation: 5578
Your question is pretty broad. If you have a specific use case you are after, we can answer your question more precisely.
Most DI frameworks I have used have singleton and transient scope you have mentioned and they usually also have per thread. Some have more and some allow you to create your own extensions to define your own scopes. Through extensions I've seen per http request, per http session, and per WCF operation.
See also...
Upvotes: 1