Skip to content

Instantly share code, notes, and snippets.

@shiena
Created November 29, 2020 13:40
Show Gist options
  • Save shiena/bd39dba2875111b722f35283ec19fcd0 to your computer and use it in GitHub Desktop.
Save shiena/bd39dba2875111b722f35283ec19fcd0 to your computer and use it in GitHub Desktop.
VContainer extension
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