Pre IL Code Generation

caution

this feature requires Unity 2019.3 or later.

VContainer has the ability to perform the meta programming part faster by generating IL code at compile time. As a result, there is no reflection at runtime, and it is expected to be 3-6x faster. It works in the IL2CPP environment.

With VContainer, for example, the following code (as IL) is automatically generated:

class ClassA
{
private sealed class __GeneratedInjector : IInjector
{
public object CreateInstance(IObjectResolver resolver, IReadOnlyList<IInjectParameter> parameters)
{
I6 fromConstructor = resolver.ResolveOrParameter<I6>("fromConstructor1", parameters);
I7 fromConstructor2 = resolver.ResolveOrParameter<I7>("fromConstructor2", parameters);
return new ClassA(fromConstructor, fromConstructor2);
}
public void Inject(object instance, IObjectResolver resolver, IReadOnlyList<IInjectParameter> parameters)
{
ClassA clasA = (ClassA)instance;
I3 service = resolver.ResolveOrParameter<I3>("service3", parameters);
I4 service2 = resolver.ResolveOrParameter<I4>("service4", parameters);
allInjectionFeatureService.MethodInjectable1(service, service2);
I5 service3 = resolver.ResolveOrParameter<I5>("service5", parameters);
I6 service4 = resolver.ResolveOrParameter<I6>("service6", parameters);
classA.MethodInjectable2(service3, service4);
classA.PrivatePropertyInjectable = resolver.Resolve<I2>();
classA.PublicPropertyInjectable = resolver.Resolve<I3>();
classA.privateFieldInjectable = resolver.Resolve<I4>();
classA.PublicFieldInjectable = resolver.Resolve<I5>();
}
}

How to enable code generation mode#

1. Add VContainerSettings in your project#

Choose Assets -> Create -> VContainer -> VContainer Settings. And select directory.

note

This menu will automatically add VContainerSettings to preload-assets.

2. Specify target assemblies#

Set the following from the inspector of VContainerSettings.asset.

  • Prepare Code Generation section
    • Enabled : enable/disable code generation feature at build time.
    • Target Assemblies : Specify the assembly you want to pre-IL generate.
      • "+" button shows valid choices
      • The Assembly specified here must reference VContainer.dll.
      • If not specified, no pre-code generation will be done
    • Namespace Filter : You can filter the target by specifying namespace.
      • "+" button shows valid choices.

3. Build your assembly#

The next time the specified assembly is compiled, VContainer will make changes to the compiled dll.

If it succeeds, it will be logged. For example:

VContainer code generation optimization for MyGame.dll 24 types (40.0355ms)

VContainer code generation optimization for VContainer.Benchmark.Fixtures 24 types (40.0355ms)