We have a console app that does a lot of different things. A LOT of different things, and what it does depends on what we pass in as command line parameters. It was originally built this way so that it only took up one licensed spot in our build server, and I've met with a bunch of resistance when suggesting splitting it out.
This app uses Simple Injector for IoC... the problem is, we've got a bunch of singleton services that are not used for any given operation, and they load with every use... this is annoyingly slow. I only want to load the dependencies that are actually used for any given operation.
It looks like there's a lot of documentation around the Lazy<TService>
, but in practice it's pretty frustrating. It seems that Lazy constructor is unaware of the container it's being used in, so it must use a parameterless constructor or a value factory that also seems unaware of the container the dependencies are in.
Is what I want to do possible with Simple Injector? I've been playing with all sorts of versions of the Lazy generic but I can't seem to get what I want.
Simple Injector allows you to register factory delegates.
// From the link above, chapter "Lazy"
container.Register<Lazy<IMyService>>(
() => new Lazy<IMyService>(container.GetInstance<RealService>));
Another possibility is to use a decorator. Simple Injector allows you to do this as well. The advantage over the first solution (where you have to call lazyService.Value.DoSomething();
) is, that you can make this change transparent. I.e. the decorator implements the service and you can call decoratedService.DoSomething();