I'm trying to understand how to create an instance of a service (for example, ITransport) with some input config at runtime using the Factory Pattern and Dependency Injection (Microsoft.Extensions.DependencyInjection). I'm pretty sure that using Ninject would make the task easier, but still, I'd like to stick with Microsoft's DI.
For example, here are our services:
public interface ITransport
{
string Type { get; }
void Move();
}
public class CarConfig { }
public class Car(CarConfig config) : ITransport
{
public string Type => nameof(Car);
public void Move() { /* logic */ }
}
public class BoatConfig { }
public class Boat(BoatConfig config) : ITransport
{
public string Type => nameof(Boat);
public void Move() { /* logic */ }
}
Or perhaps it's better like this:
public class Car(IConfig config) : ITransport {...}
public class Boat(IConfig config) : ITransport {...}
Each of them has some input configuration in the constructor. Also, each of them will have different dependencies, so they need to be created only through DI.
Here's the factory for getting the necessary service (transport):
public interface ITransportFactory
{
ITransport GetTransport(string type, object config);
// or
ITransport GetTransport(string type, IConfig config);
}
I see a dozen ways to approach implementing this, but I'm not sure if any of them will work. Please help.
ActivatorUtilities.CreateInstancemethods that you can use inside yourITransportFactoryimplementation. It allows you to supply the runtime data and it will compose the desired instance based on known dependencies and runtime data.