Suppose I have the Service
that receives dependencies via constructor but also needs to be initialized with custom data (context) before it can be used:
public interface IService
{
void Initialize(Context context);
void DoSomething();
void DoOtherThing();
}
public class Service : IService
{
private readonly object dependency1;
private readonly object dependency2;
private readonly object dependency3;
public Service(
object dependency1,
object dependency2,
object dependency3)
{
this.dependency1 = dependency1 ?? throw new ArgumentNullException(nameof(dependency1));
this.dependency2 = dependency2 ?? throw new ArgumentNullException(nameof(dependency2));
this.dependency3 = dependency3 ?? throw new ArgumentNullException(nameof(dependency3));
}
public void Initialize(Context context)
{
// Initialize state based on context
// Heavy, long running operation
}
public void DoSomething()
{
// ...
}
public void DoOtherThing()
{
// ...
}
}
public class Context
{
public int Value1;
public string Value2;
public string Value3;
}
Now - the context data is not know beforehand so I cannot register it as a dependency and use DI to inject it into the service
This is how example client looks like:
public class Client
{
private readonly IService service;
public Client(IService service)
{
this.service = service ?? throw new ArgumentNullException(nameof(service));
}
public void OnStartup()
{
service.Initialize(new Context
{
Value1 = 123,
Value2 = "my data",
Value3 = "abcd"
});
}
public void Execute()
{
service.DoSomething();
service.DoOtherThing();
}
}
As you can see - there are temporal coupling and initialize method code smells involved, because I first need to call service.Initialize
to be able to call service.DoSomething
and service.DoOtherThing
afterwards.
What are the other approaches in which I can eliminate these problems?
Additional clarification of the behavior:
Each instance of the client needs to have it's own instance of the service initialized with client's specific context data. So, that context data is not static or known in advance so it cannot be injected by DI in the constructor.