Myioc follows the Register-resolve-release mode.
Let's first look at how to register a service. Registering a service is actually very simple. Create an iobjectcontainer instance and call any register method of the instance. See the Code:
1 var container = new ObjectContainer(true);2 container.Register<IService, MyService>();
View code
Here are some notes: First, let's talk about the construction of the objectcontainer object. This object contains several constructors.
1 public ObjectContainer()2 public ObjectContainer(bool useLightweightCodeGeneration)3 public ObjectContainer(bool useLightweightCodeGeneration, IConstructorSelector constructorSelector)4 public ObjectContainer(ContainerOption option)
View code
These constructors are used to specify containeroption.
The register method contains multiple overloading methods. The register method mainly provides four registration methods:
- Register a constant or an existing instance object.
- Register a service using func.
- Register the service in type mode and specify the reflection mode to build the object.
- Register the service in type mode and specify to use emit to build the object.
Optimization suggestions:
- Try to use the generic method for registration. This avoids reflection overhead and improves performance when registering a service.
- Use the func method as little as possible for registration, because in this way, the framework will not be able to track service dependencies, and thus cannot notify service users when their dependencies are registered, logged out, activated, or stopped. In addition, when using the func Method for registration, the framework needs to query Dependencies from the registry every time, so the cache cannot be used to improve performance.
- If the lifecycle of the registered service is iner or a Singleton, do not explicitly specify the emit method (this method is not used by default) to build objects by dynamically generating code, because this type of lifecycle object is constructed only once and then reused, it is not worth the overhead of dynamic generation of code.
Basic use of my. IOC-simple example