Skip to content

Instantly share code, notes, and snippets.

@PoisonousJohn
Last active February 21, 2018 08:28
Show Gist options
  • Save PoisonousJohn/61f45acde59723d317c21b06f26dfa6b to your computer and use it in GitHub Desktop.
Save PoisonousJohn/61f45acde59723d317c21b06f26dfa6b to your computer and use it in GitHub Desktop.
Solving cross-dependency with Lazy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Services
{
public static Lazy<ILogger> log = new Lazy<ILogger>(() =>
{
return new UserIdUnityLogger(api);
});
public static Lazy<IAPIService> api = new Lazy<IAPIService>(
() =>
{
return new APIService(log);
});
}
public interface IAPIService
{
string UserId { get; }
void Login();
}
public interface IAnalyticsService
{
void LogEvent(string msg);
}
public interface ILogger
{
void Log(string msg);
void Warning(string msg);
void Error(string msg);
}
public class APIService : IAPIService
{
private readonly Lazy<ILogger> _logger;
public APIService(Lazy<ILogger> logger)
{
_logger = logger;
}
public string UserId { get; private set; }
public void Login()
{
_logger.Value.Log("Login started");
UserId = "registeredUser1";
_logger.Value.Log("Login ended");
}
}
public class UserIdUnityLogger : ILogger
{
public UserIdUnityLogger(Lazy<IAPIService> api)
{
_api = api;
}
public void Error(string msg)
{
Debug.LogError(Format(msg));
}
public void Log(string msg)
{
Debug.Log(Format(msg));
}
public void Warning(string msg)
{
Debug.LogWarning(Format(msg));
}
private string Format(string msg)
{
return string.Format("<{0}>: {1}", !_api.IsValueCreated
|| string.IsNullOrEmpty(_api.Value.UserId)
? "anonymous"
: _api.Value.UserId, msg);
}
private readonly Lazy<IAPIService> _api;
}
public class Loader : MonoBehaviour {
private void Awake() {
Services.log.Value.Log("Loading started");
Services.api.Value.Login();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment