2

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.

1

1 Answer 1

9

Rather than registering SomeDIService directly in your DI container, you can register a factory for the service:

public class SomeDIServiceFactory
{
    SomeDIService Create(string requiredProperty) => new SomeDIService(requiredProperty);
}

Now just let your DI framework inject SomeDIServiceFactory into your Client class and it can use the factory to obtain an appropriate instance of the service:

public class Client
{
    public Client(SomeDIServiceFactory factory)
    {
        _someDIService = factory.Create("xyzzy");
    }
}

You do need to be careful about managing the different instances of your service and their lifetimes in this scenario, but that's not a problem which has been introduced by DI.

1
  • I do have a very similar follow up question if you're up for a quick discussion in chat ... this question is not needing of a brand new post. Thanks!
    – spencer741
    Commented Apr 11, 2021 at 18:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.