Skip to content

Commit a3f9dd1

Browse files
committed
Fixed SingletonCouldDependedOnTransientThoughtFuncDependency
1 parent 855e500 commit a3f9dd1

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

BTDB/IOC/ContainerImpl.cs

+4
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ public object ResolveKeyed(object? key, Type type)
106106

107107
if (type.IsDelegate())
108108
{
109+
if (ctxImpl.VerifySingletons) return (_, _) => null;
109110
if (IContainer.FactoryRegistry.TryGetValue(type.TypeHandle.Value, out var factory))
110111
{
111112
return factory(this, ctx);
@@ -117,6 +118,7 @@ public object ResolveKeyed(object? key, Type type)
117118
var genericTypeDefinition = type.GetGenericTypeDefinition();
118119
if (genericTypeDefinition == typeof(Func<>))
119120
{
121+
if (ctxImpl.VerifySingletons) return (_, _) => null;
120122
var nestedType = type.GetGenericArguments()[0];
121123
var nestedFactory = CreateFactory(ctx, nestedType, key);
122124
if (nestedFactory == null) return null;
@@ -131,6 +133,7 @@ public object ResolveKeyed(object? key, Type type)
131133

132134
if (genericTypeDefinition == typeof(Func<,>))
133135
{
136+
if (ctxImpl.VerifySingletons) return (_, _) => null;
134137
var genericArguments = type.GetGenericArguments();
135138
var nestedType = genericArguments[1];
136139
if (genericArguments[0] == typeof(IContainer))
@@ -313,6 +316,7 @@ public object ResolveKeyed(object? key, Type type)
313316
{
314317
if (cReg.Lifetime == Lifetime.Singleton && cReg.SingletonId != uint.MaxValue)
315318
{
319+
if (ctxImpl.VerifySingletons) return (_, _) => null;
316320
var singletonInstance = Volatile.Read(ref Singletons[cReg.SingletonId]);
317321
// If Singleton is just being created return waiting factory
318322
if (singletonInstance is SingletonLocker)

BTDBTest/IOCTests.cs

+12
Original file line numberDiff line numberDiff line change
@@ -1637,6 +1637,18 @@ public void ComplexFuncDependency()
16371637
Assert.NotNull(obj);
16381638
}
16391639

1640+
[Fact]
1641+
public void SingletonCouldDependedOnTransientThoughtFuncDependency()
1642+
{
1643+
var builder = new ContainerBuilder();
1644+
builder.RegisterType<KlassWithFuncDependency>().SingleInstance();
1645+
builder.RegisterType<Logger>().As<ILogger>().SingleInstance();
1646+
builder.RegisterType<ErrorHandler>().As<IErrorHandler>();
1647+
var container = builder.BuildAndVerify();
1648+
var obj = container.Resolve<KlassWithFuncDependency>();
1649+
Assert.NotNull(obj);
1650+
}
1651+
16401652
[Fact]
16411653
public void ComplexFuncDependency2()
16421654
{

0 commit comments

Comments
 (0)