-
Notifications
You must be signed in to change notification settings - Fork 29
Pure.DI in Unity3d #83
Unanswered
AndreyProkopyev-azur
asked this question in
Q&A
-
Hi,
Do you have examples of using Pure.DI in Unity3d?
Code generation works well, however Unity3d scripts do not have single entry point and it's MonoBehaviours don't have constructors, so there is only service locator approach or assigning fields via roots.
public class ClientScript : MonoBehaviour { private Boot.IService _service; private void Start() { _service = Composition.Instance.Service; // root _service = Composition.Instance.Resolve<Boot.IService>(); // service locator } }
Is there a way to implement something like this
public class ClientScript : MonoBehaviour { private Boot.IService _service; private void Start() { Composition.Instance.Inject(this); // assigns value to _service } }
?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
Yes, it's possible. Please see this example:
using Pure.DI; var composition = new Composition(); var script = new ClientScript(); script = composition.BuildUp(script); DI.Setup(nameof(Composition)) .Bind().To<Service1>() .Bind().To<Service2>() .Bind().To<ClientScript>(ctx => { ctx.Inject("from arg", out ClientScript script); ctx.BuildUp(script); return script; }) .RootArg<ClientScript>("clientScript", "from arg") .Root<ClientScript>("BuildUp"); class ClientScript { [Ordinal(1)] public IService1 service1; [Ordinal(2)] public IService2 service2; } interface IService1 { }; internal class Service1 : IService1 { }; interface IService2 { }; internal class Service2 : IService2 { };
The BuildUp method is as follows:
public ClientScript BuildUp(ClientScript clientScript) { clientScript.service1 = new Service1(); clientScript.service2 = new Service2(); return clientScript; }
Beta Was this translation helpful? Give feedback.
All reactions
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment