-
I have a use case where I want to use singletons and I want to guarantee that those singletons are only constructed once. However, I'm not sure how to register the types in the assembly to do this - I'm noticing that instances are created for each As an example, say we have type _diContainer
.RegisterAssemblyContaining<IBaseInterface>(
type => typeof(IBaseInterface).IsAssignableFrom(type),
configurator: opt => opt.WithSingletonLifetime()
); and then I resolve them both: var a = container.Resolve<A>();
var b = container.Resolve<B>(); Later I want to have both instances in an array: var allOfThem = containers.ResolveAll<IBaseInterface>(); What I'm seeing is that For convenience I've written a test (in the style of AssemblyTests.cs) of what I'm trying to accomplish: [Fact]
public void ResolveAllResolvesExistingInstance()
{
using var container = new StashboxContainer();
container.RegisterAssemblyContaining<ITA_T1>(
type => typeof(ITA_T1).IsAssignableFrom(type),
configurator: opt => opt.WithSingletonLifetime()
);
var all = container.ResolveAll<ITA_T1>();
var instance = container.Resolve<TA_T1>();
// sanity test that there is a TA_T1
Assert.Contains(all, it => it is TA_T1);
// however they aren't the same instance
Assert.Contains(all, it => it == instance);
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
It looks like I can get the desired behavior by manually registering the types in the assembly and using using var container = new StashboxContainer();
foreach (var type in typeof(ITA_T1).Assembly.GetTypes()
.Where(it => it.Name.StartsWith("TA_") && it.IsClass && !it.IsAbstract))
{
container.Register(
type,
configurator: opt => opt.WithSingletonLifetime()
.AsImplementedTypes()
);
}
var all = container.ResolveAll<ITA_T1>();
// sanity test that there is a TA_T1
Assert.Contains(all, it => it is TA_T1);
// however they aren't the same instance
var instance = container.Resolve<TA_T1>();
Assert.Contains(all, it => it == instance); |
Beta Was this translation helpful? Give feedback.
It looks like I can get the desired behavior by manually registering the types in the assembly and using
AsImplementedTypes
: