I need to be able to pass a connection string into some of my service implementations. I am doing this in the constructor. The connection string is configurable by user will be
Further to @Tseng's extremely helpful answer, I found I could also adapt it to use delegates:
public delegate INestedService INestedServiceFactory(string connectionString);
services.AddTransient((provider) => new INestedServiceFactory(
(connectionString) => new NestedService(connectionString)
));
Implemented in RootService
in the same way @Tseng suggested:
public class RootService : IRootService
{
public INestedService NestedService { get; set; }
public RootService(INestedServiceFactory nestedServiceFactory)
{
NestedService = nestedServiceFactory("ConnectionStringHere");
}
public void DoSomething()
{
// implement
}
}
I prefer this approach for cases where I need an instance of a factory in a class, as it means I can have a property of type INestedServiceFactory
rather than Func
.