From 5bb68ba301086630a81e3209cc34b615c0edb8d3 Mon Sep 17 00:00:00 2001 From: labbbirder <502100554@qq.com> Date: Wed, 18 Oct 2023 20:11:45 +0800 Subject: [PATCH] feat: more controls on ServiceContainer --- Runtime/ClassicalUsages/ServiceContainer.cs | 29 ++++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/Runtime/ClassicalUsages/ServiceContainer.cs b/Runtime/ClassicalUsages/ServiceContainer.cs index e9cc56f..1d02799 100644 --- a/Runtime/ClassicalUsages/ServiceContainer.cs +++ b/Runtime/ClassicalUsages/ServiceContainer.cs @@ -127,6 +127,11 @@ static Info GetProperInfoAndCache(Type desiredType, Type declaringType) return lutInfos[(desiredType, declaringType)] = info; } + static object CreateInstance(Info info) + { + if (info.creator != null) return info.creator(); + return Activator.CreateInstance(info.resultType, info.constructorArguments); + } public static object Get(Type desiredType, Type declaringType = null) { @@ -136,13 +141,13 @@ public static object Get(Type desiredType, Type declaringType = null) { if (!singletons.TryGetValue(info.resultType, out var inst)) { - singletons[info.resultType] = inst = Activator.CreateInstance(info.resultType, info.constructorArguments); + singletons[info.resultType] = inst = CreateInstance(info); } return inst; } else { - return Activator.CreateInstance(info.resultType); + return CreateInstance(info); } } @@ -165,7 +170,17 @@ public static ServiceScopeMode GetScopeMode(Type declaringType = null /// public static BindDeclaringContext In() { - return new BindDeclaringContext(typeof(T)); + return In(typeof(T)); + } + + /// + /// for members declared in ... + /// + /// + /// + public static BindDeclaringContext In(Type targetType) + { + return new BindDeclaringContext(targetType); } /// @@ -244,6 +259,7 @@ public BindSourceContext AsSingle(bool noLazy = false) resultType = typeof(TDest), scopeMode = scopeMode, constructorArguments = arguments, + creator = null, }; if (noLazy && scopeMode == ServiceScopeMode.Single) { @@ -260,8 +276,12 @@ public BindSourceContext AsSingle(bool noLazy = false) resultType = typeof(TDest), scopeMode = scopeMode, // constructorArguments = arguments, + creator = () => creator() }; - ServiceContainer.singletons[typeof(TDest)] = creator(); + if (noLazy && scopeMode == ServiceScopeMode.Single) + { + ServiceContainer.Get(desiredType, declaringType); + } } } @@ -270,5 +290,6 @@ struct Info public Type resultType; public ServiceScopeMode scopeMode; public object[] constructorArguments; + public Func creator; } } \ No newline at end of file