Usually two patterns are used to use rarely needed objects, which are very expensive to create. The first template uses the factory, as suggested by David Favre. The other is using a proxy.
From a design point of view, a proxy server is probably the cleanest solution, although it may take more code to implement it. This is the cleanest because the application may be completely unaware of it, because you do not need an additional interface (since you need a factory approach).
Here is a simple example with some interface and expensive implementation:
interface IAmAService { void DoSomething(); } class ExpensiveImpl : IAmAService { private object x = [some expensive init]; void IAmAService.DoSomething() { } }
No, you can implement a proxy server based on this interface, which may delay the creation of this implementation:
class ServiceProxy : IAmAService { private readonly Func<IAmAService> factory; private IAmAService instance; public ServiceProxy(Func<IAmAService> factory) { this.factory = factory; } void IAmAService.DoSomething() { this.GetInstance().DoSomething(); } private IAmAService GetInstance() {
This proxy class accepts the factory delegate as a dependency, just like David Fyvre described in his answer, but the application should not depend on Func<IAmAService> , but may just depend on IAmAService .
Now, instead of typing ExpensiveImpl you can enter ServiceProxy in other instances:
// Create the proxy IAmAService service = new ServiceProxy(() => new ExpensiveImpl()); // Inject it into whatever you wish, such as: var customerService = new CustomerService(service);
source share