I use the Abstract Factory pattern whenever I need to get the value of the runtime has been introduced as a dependency.
Define Factory Interface
public interface IFooFactory { Foo CreateFoo(); }
Deploy the interface using autofac delegate support. If you are running a dependency on any delegate, autofac will create an implementation for you with all the dependencies except the dependencies that the delegate accepts.
public class FooFactory : IFooFactory { private readonly Func<FooSettings, Foo> creationFunc; private readonly ISettingsProvider settingsProvider; public FooFactory(Func<FooSettings, Foo> creationFunc, ISettingsProvider settingsProvider) { if (creationFunc == null) throw new ArgumentNullException("creationFunc"); if (settingsProvider == null) throw new ArgumentNullException("settingsProvider"); this.creationFunc = creationFunc; this.settingsProvider = settingsProvider; } public Foo CreateFoo() { var providerSettings = settingsProvider.GetSettings("fooSettings"); var fooSettings = new FooSettings(providerSettings[0], providerSettings[1]); return creationFunc(fooSettings); } }
Take a dependency on IFooFactory instead of ISettingsProvider
public class ClientClass { private readonly IFooFactory fooFactory; public ClientClass(IFooFactory fooFactory) { this.fooFactory = fooFactory; } public void DoSomething() { var foo = fooFactory.CreateFoo();
And of course, register a factory
builder.RegisterType<FooFactory>().As<IFooFactory>();
source share