Wiring this up with the IoC container is going to be tricky, but it could be simplified if the ISetup
was injected in a factory class' constructor - first we need an abstraction for the Hub
:
public interface IHub
{
void Start();
}
Now let's create a factory class whose sole responsibility is to create IHub
instances:
public class SetupHubFactory
{
private readonly ISetup _setup;
public SetupHubFactory(ISetup setup)
{
_setup = setup;
}
public SetupHubIHub Create(Action<double> updateProgress)
{
return new SetupHub(_setup, updateProgress);
}
}
public class SetupHubFactory : IHubFactory<SetupHub>IHubFactory
{
// ...
}
public interface IHubFactory<THub> where THub : HubIHubFactory
{
THubIHub Create(action<double> updateProgress);
}
This IHubFactory<THub>IHubFactory
is an abstract factory (a generic one) - the client code receives any HubFactory, and works against an abstraction, instead of being tied to a single specific implementation:
public class ClientObject
{
private readonly IHubFactory _hubFactory;
public ClientObject(IHubFactory hubFactory)
{
_hubFactory = hubFactory;
}
public void DoSomething()
{
// hub is of type IHub - ClientObject isn't tied to a specific implementation.
// inject a new implementation of the `IHubFactory` and no changes needed,
// this method will create an instance of the new hub implementation:
var hub = _hubFactory.Create(UpdateProgressBar);
hub.Start();
}
private void UpdateProgressBar(double progress)
{
// ...
}
}