Created
November 29, 2020 13:40
-
-
Save shiena/bd39dba2875111b722f35283ec19fcd0 to your computer and use it in GitHub Desktop.
VContainer extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using VContainer.Unity; | |
namespace VContainer | |
{ | |
public static class IContainerBuilderExtension | |
{ | |
public static RegistrationBuilder RegisterComponentInGameObject<T>(this IContainerBuilder builder, | |
GameObject gameObject = default) | |
where T : MonoBehaviour | |
{ | |
if (gameObject == default) | |
{ | |
var lifetimeScope = (LifetimeScope)builder.ApplicationOrigin; | |
gameObject = lifetimeScope.gameObject; | |
} | |
var component = gameObject.GetComponentInChildren<T>(true); | |
if (component == null) | |
{ | |
throw new VContainerException(typeof(T), | |
$"Component {typeof(T)} is not in this GameObject {gameObject.name}"); | |
} | |
return builder.RegisterInstance(component).As(typeof(MonoBehaviour), typeof(T)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment