مهدی خانزادی
۲۷ مرداد ۱۴۰۵
The two previous parts covered the concepts; this one is hands-on. Install danceable/container, bind and resolve services, control their lifetime with bind.Singleton() and bind.Lazy(), and let the container call your functions — then organize the whole thing with danceable/provider's Register / Boot / Terminate lifecycle.
In this part we introduce
danceable/containeranddanceable/providerfor dependency management and service lifecycle management, and then use them to build a multilingual blog.
danceable/container as a service container in GoIn the previous part we covered the service container concept. Here we get to know danceable/container and learn how to use it.
Installing the package:
To create a container, use the New method:
With the Bind method we tell the container how to create a service:
With the Resolve method we ask the container to hand us a MongoDB connection:
Every time we call Resolve, the function we registered with the container is invoked, a value of that type is created, and it's placed into our variable. If the last value the function returns is an error, Resolve returns that error.
Sometimes we need only one instance of a service to exist. In that case we can pass bind.Singleton() to the Bind method:
With bind.Singleton(), no matter how many times we call Resolve, only one *mongo.Client is created and shared.
Note 1: By default, the moment you call Bind the function you passed is invoked once, so that any error surfaces at bind time. With bind.Lazy() you can tell the container to defer running that function until the first Resolve.
Note 2: With bind.Singleton() the container caches the result of the first run of the bound function and shares it on every Resolve.
The Call method asks the container to supply a function's parameters and invoke it:
The Fill method can also populate a struct's fields through the container. See the danceable/container documentation for more.
danceable/provider as a service provider in GoIn the previous part we covered the service provider concept. Here we get to know danceable/provider and learn how to use it.
Installing the package:
This package lets you define providers that take on binding your services and managing their lifecycle.
Every provider has at least these three methods:
Once the providers exist, register them and then run them with the Run method:
Calling Run goes through these stages:
Register method of every provider runs, in the order they were registered.Boot method of every provider runs, in the order they were registered.Terminate method of every provider runs, in the reverse of the order they were registered.Note: According to the documentation, the provider order can be changed by defining an Order method.
For more on danceable/provider, see its documentation.