I am using some C# pseudo to illustrate here. Below, you will see a Service and a Client (in the context of using DI).
The service has a required property that will need to be initialized by the Client.
Typically, the client would instantiate an object, and pass any required data through the constructor.
Using DI, however, the object is instantiated and passed to the Client class
.
//Service:
public class SomeDIService
{
string RequiredProperty {get;set;}
public SomeDIService(...)
{
...
}
}
//Client:
public class Client
{
SomeDIService _someDIService {get;set;}
public Client(SomeDIService someDIService)
{
_someDIService = someDIService;
}
}
My question is this:
Let's say that the required property that SomeDIService
needs can only be provided by the Client class
. Since SomeDIService
is already instantiated, the data to initialize the required property cannot be passed via the constructor.
From your experience, do DI services typically have an initialize method that will initialize several properties? I realize that within the Client class
I could just set the required property in SomeDIService
directly... I am pondering on what makes the most sense when designing these DI services to make my services more comprehensible to other developers.
As I am writing this, I realize this is not really a DI question, but a very basic OOP question. And I understand this leans more toward opinion or the dreaded "best practice" question, but as I am learning about some basic DI techniques, I also wonder if my approach is creeping on some anti-pattern. Any advice on this will be appreciated.
I'll say that I do not believe this is a duplicate, but I will link it here for reference sake.