When using the IOC framework, we generally recommend that you register (Register) and resolve services in a location called composition root (for its meaning, see the following note. This approach aims to minimize the IOC framework dependencies of applications by limiting IOC usage.
Although this mode can well decouple the application and IOC framework, so that we can easily replace the IOC framework as needed, it also brings about a problem: do we have to register all services when the program starts? Some services may not be used immediately, and some services may not even be used. In this case, if all the services are registered to the container when the program starts, the result will undoubtedly slow down the startup speed of the program and increase the memory consumption.
To solve this problem, we provide a solution for delayed registration in my. IOC. Its principle is actually very simple: when the application is directed to my. when the IOC container requests a service, if the service is not yet registered, the container will trigger an objectbuilderrequested event and provide the requested contract type (contract type) in the event parameters) and injectioninfo, and subscribed to the event handler) at this time, you can decide whether to register the corresponding service to the container based on the contract type and injection point information to meet the application requirements.
The usage is simple. The sample code is as follows:
using System;using System.Diagnostics;using My.Ioc;namespace LazyRegistration{ public interface ILazyService { } public class LazyService : ILazyService { } class Program { static bool _eventHandled = false; static void Main(string[] args) { IObjectContainer container = new ObjectContainer(false); container.ObjectBuilderRequested += OnObjectBuilderRequested; var lazy = container.Resolve<ILazyService>(); Debug.Assert(lazy != null); Debug.Assert(lazy is LazyService); Console.WriteLine(_eventHandled); Console.ReadLine(); } static void OnObjectBuilderRequested(ObjectBuilderRequestedEventArgs args) { if (args.ContractType == typeof (ILazyService)) { args.Register<ILazyService, LazyService>(); _eventHandled = true; } } }}
Note:
The definition of composition root is "the location of each module of a combined application. There should be only one such location in an application, which is usually the entry point of the application. For example, for console applications, this location is the main function; for ASP. for the net MVC application, this location may be global. asax; for WPF applications, this location is application. onstartup method... ".
Source code can be downloaded from here.
My. IOC sample code -- use the objectbuilderrequested event to implement delayed registration