How is it possible to pass a static class to an object via Dependency Injection?
For example Carbon uses static methods:
$tomorrow = Carbon::now()->addDay();
I have services that depend on Carbon, and currently I'm using the library in the dependancies without injecting them. But, this increases coupling and I'd like to instead pass it in via DI.
I have the following controller:
$container['App\Controllers\GroupController'] = function($ci) {
return new App\Controllers\GroupController(
$ci->Logger,
$ci->GroupService,
$ci->JWT
);
};
How do I pass Carbon into that?
So, today we will see how we can handle these kinds of operations, so we can achieve Dependency Injection with static classes in . NET Core. There is simple logic if we cant use a constructor with the static class we can create one method in which we can pass dependency while run time. to do that we will use Startup.
You can't inject a static logger. You have to either change it to an instance logger (if you can), or wrap it in an instance logger (that will call the static).
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.
Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.
Static methods are called static
because they can be invoked without instantiating class object. So, you cannot pass static class
(even static class
is not a legal term).
Available options are:
Pass object of Carbon:now()
to your constructor:
$container['App\Controllers\GroupController'] = function($ci) {
return new App\Controllers\GroupController(
$ci->Logger,
$ci->GroupService,
$ci->JWT,
\Carbon:now() // here
);
};
Pass a callable object:
$container['App\Controllers\GroupController'] = function($ci) {
return new App\Controllers\GroupController(
$ci->Logger,
$ci->GroupService,
$ci->JWT,
['\Carbon', 'now'] // here or '\Carbon::now'
);
};
And later create Carbon
instance using something like:
$carb_obj = call_user_func(['\Carbon', 'now']);
$carb_obj = call_user_func('\Carbon::now');
Using second option you can define function name dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With