I have a simple service manager with a name ServiceManager
that has two methods. Create()
creates an instance of the service. Provide()
returns the previously created service.
I have a basic implementation that works, but I wonder if there is a cleaner way. This is my main implementation ServiceManager
:
public class ServiceManager : MonoBehaviour
{
private Dictionary<Type, MonoBehaviour> services = new Dictionary<Type, MonoBehaviour>();
public void Create<T>() where T : MonoBehaviour
{
GameObject serviceObject = new GameObject(typeof(T).Name);
serviceObject.transform.SetParent(transform);
T service = serviceObject.AddComponent<T>();
services.Add(typeof(T), service);
}
public T Provide<T>() where T : MonoBehaviour
{
return (T)services[typeof(T)];
}
}
Using the service is simple:
public class ServiceTest : MonoBehaviour
{
private void Start()
{
ServiceManager services = FindObjectOfType<ServiceManager>();
services.Create<MapService>();
services.Create<InteractionService>();
}
private void Example()
{
ServiceManager services = FindObjectOfType<ServiceManager>();
MapService map = services.Provide<MapService>();
}
}
My question is about ServiceManager.Provide()
. Note the cast in T after receiving the item from the dictionary. This seems very unclean and makes me wonder if I am missing something about how generics work in C #. Are there other / better ways to do what I'm trying to accomplish?