Initial commit
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace BracerLib.DI
|
||||
{
|
||||
public delegate object FactoryFunc(DependencyProvider provider);
|
||||
|
||||
public static class DependencyFactory
|
||||
{
|
||||
public static FactoryFunc FromClass<T>() where T : class, new()
|
||||
{
|
||||
return provider =>
|
||||
{
|
||||
var type = typeof(T);
|
||||
var obj = FormatterServices.GetUninitializedObject(type);
|
||||
|
||||
provider.Inject(obj);
|
||||
|
||||
type.GetConstructor(Type.EmptyTypes)?.Invoke(obj, null);
|
||||
|
||||
return (T)obj;
|
||||
};
|
||||
}
|
||||
|
||||
public static FactoryFunc FromGameObject<T>(T instance) where T : MonoBehaviour
|
||||
{
|
||||
return dependencies =>
|
||||
{
|
||||
var children = instance.GetComponentsInChildren<MonoBehaviour>(true);
|
||||
foreach (var child in children)
|
||||
dependencies.Inject(child);
|
||||
|
||||
return instance;
|
||||
};
|
||||
}
|
||||
|
||||
public static FactoryFunc FromPrefab<T>(T prefab) where T : MonoBehaviour
|
||||
{
|
||||
return provider =>
|
||||
{
|
||||
var prefabObj = prefab.gameObject;
|
||||
var wasActive = prefabObj.activeSelf;
|
||||
prefabObj.SetActive(false);
|
||||
var instance = Object.Instantiate(prefab);
|
||||
prefabObj.SetActive(wasActive);
|
||||
var children = instance.GetComponentsInChildren<MonoBehaviour>(true);
|
||||
|
||||
foreach (var child in children)
|
||||
provider.Inject(child);
|
||||
|
||||
instance.gameObject.SetActive(wasActive);
|
||||
|
||||
return instance.GetComponent<T>();
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user