Type registered with Singleton instantiating multiple times #649
-
How can i ensure that internal class Program
{
static void Main(string[] args)
{
var container = new Container();
// Registering singletons
container.Register<RuleMenuOptionItem>(Reuse.Singleton);
container.Register<INavMenuItem, RuleMenuOptionItem>(Reuse.Singleton);
// Resolve instances
var instance1 = container.Resolve<RuleMenuOptionItem>();
var instance2 = container.Resolve<INavMenuItem>();
var lazyInstance = container.Resolve<Lazy<IEnumerable<INavMenuItem>>>();
// Check if instances are the same
Console.WriteLine(ReferenceEquals(instance1, instance2)); // Should be True
// Trigger Lazy loading
var lazyItems = lazyInstance.Value;
foreach (var item in lazyItems)
{
Console.WriteLine(item.GetType().Name);
}
}
}
public interface INavMenuItem { }
public class RuleMenuOptionItem : INavMenuItem
{
private static int _instanceCount = 0;
public RuleMenuOptionItem()
{
_instanceCount++;
Console.WriteLine($"RuleMenuOptionItem instantiated {_instanceCount} times");
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Replace the registration with // Registering singletons
container.Register<RuleMenuOptionItem>(Reuse.Singleton);
container.Register<INavMenuItem, RuleMenuOptionItem>(Reuse.Singleton); with container.RegisterMany<RuleMenuOptionItem>(Reuse.Singleton); Check the docs. |
Beta Was this translation helpful? Give feedback.
-
Yes, this is working thanks. However, I came across another approach from here and worked.
What is the difference between the two if you can briefly elaborate for better understanding? Further, is there any article to learn more about it. |
Beta Was this translation helpful? Give feedback.
-
The one with Made.Of has more overhead without any benefits for your specific case. RegisterMany is specifically designed for your case. Another viable option is to use RegisterMapping, which designed to add services to the already registered implementation. |
Beta Was this translation helpful? Give feedback.
@furqansafdar
Replace the registration with
RegisterMany
:with
Check the docs.