Skip to content

Commit

Permalink
feat: more controls on ServiceContainer
Browse files Browse the repository at this point in the history
  • Loading branch information
labbbirder committed Oct 18, 2023
1 parent b6655f0 commit 5bb68ba
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions Runtime/ClassicalUsages/ServiceContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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);
}
}

Expand All @@ -165,7 +170,17 @@ public static ServiceScopeMode GetScopeMode<TContract>(Type declaringType = null
/// <returns></returns>
public static BindDeclaringContext In<T>()
{
return new BindDeclaringContext(typeof(T));
return In(typeof(T));
}

/// <summary>
/// for members declared in <paramref name="targetType"/> ...
/// </summary>
/// <param name="targetType"></param>
/// <returns></returns>
public static BindDeclaringContext In(Type targetType)
{
return new BindDeclaringContext(targetType);
}

/// <summary>
Expand Down Expand Up @@ -244,6 +259,7 @@ public BindSourceContext<TSource> AsSingle(bool noLazy = false)
resultType = typeof(TDest),
scopeMode = scopeMode,
constructorArguments = arguments,
creator = null,
};
if (noLazy && scopeMode == ServiceScopeMode.Single)
{
Expand All @@ -260,8 +276,12 @@ public BindSourceContext<TSource> 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);
}
}
}

Expand All @@ -270,5 +290,6 @@ struct Info
public Type resultType;
public ServiceScopeMode scopeMode;
public object[] constructorArguments;
public Func<object> creator;
}
}

0 comments on commit 5bb68ba

Please sign in to comment.