I have registered 5 derived classes for the same interface using named instances. All these classes are registered as Singleton
For<IBaseInterface>().Singleton().Use<DerivedClass1>().Named("Derived1");
For<IBaseInterface>().Singleton().Use<DerivedClass2>().Named("Derived2");
For<IBaseInterface>().Singleton().Use<DerivedClass3>().Named("Derived3");
There is a static class which resolves the instance based on input. However I observed that every call to ObjectFactory.GetInstance returns new instances on every request instead of a Singleton. There are no threads in the application as well.
Any idea on why this is happening?
Edit:
Does a static resolution helper cause any issues? This is the way I am resolving the instance. Singleton works properly in a sample application but it doesnt work on my machine.
To add some more details - the project is MVC Web API and I am testing on local IIS. I am positive there are no user created threads in the application.
public static class Resolver
{
public static IBaseInterface GetHelper(string inputParam)
{
if inputParam is "Case1"
return ObjectFactory.GetInstance<IBaseInterface>("Derived1")
//Similarly for other instances
}
}
I would be careful that you are using the Dependency Injection container correctly. For instance, the Resolver
class that you show in your post, is this acting as simply a type of Factory or Provider?
When using Dependency Injection, you want to be sure and follow the RRR pattern: Register, Resolve, and Release. Registration should happen in your application's composition root. For ASP.Net MVC, it's ususally somewhere within Global.asax
, such as in the code-behind's Application_Start
method. This should only occur once per Application Pool startup (for IIS).
If by chance you are passing the container around (or an object which instantiates a container and performs registration and later resolution)—which you shouldn't do—it's possible that these "different instances" you are seeing are coming from two different containers. Even if you aren't passing around the container, per se, if you are instantiating your container somewhere such that, after each request, the container is garbage collected and recreated on subsequent requests, you may see a "different instance" of the singleton objects being resolved and instantiated; again, each coming from a different instance of the container. One way you can verify this is to verify that the objects resolved from your container are also coming from the same container instance.
HTH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With