Skip to main content

Plain C# Classes

There are various ways to use Register. Let's take the following complex type as an example.

class ServiceA : IServiceA, IInputPort, IDisposable { /* ... */ }

Register Concrete Type

builder.Register<ServiceA>(Lifetime.Singleton);

It can resolve like this:

class ClassA
{
public ClassA(ServiceA serviceA) { /* ... */ }
}

Register as Interface

builder.Register<IServiceA, ServiceA>();

It can resolve like this:

class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}

Register as Multiple Interfaces

builder.Register<ServiceA>(Lifetime.Singleton)
.As<IServiceA, IInputPort>();

It can resolve like this:

class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}

class ClassB
{
public ClassB(IInputPort inputPort) { /* ... */ }
}

Register All Implemented Interfaces Automatically

builder.Register<ServiceA>(Lifetime.Singleton)
.AsImplementedInterfaces();

It can resolve like this:

class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}

class ClassB
{
public ClassB(IInputPort inputPort) { /* ... */ }
}

Register All Implemented Interfaces and Concrete Type

builder.Register<ServiceA>(Lifetime.Singleton)
.AsImplementedInterfaces()
.AsSelf();

It can resolve like this:

class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}

class ClassB
{
public ClassB(IInputPort inputPort) { /* ... */ }
}

class ClassC
{
public ClassC(ServiceA serviceA) { /* ... */ }
}

Register Lifecycle Marker Interfaces

class GameController : IStartable, ITickable, IDisposable { /* ... */ }
builder.RegisterEntryPoint<GameController>();
note

This is similar to Register<GameController>(Lifetime.Singleton).AsImplementedInterfaces() . The key difference is whether it runs in PlayerLoopSystem or not.

If you want to customize the exception handling for entry points, you can register a callback with the following.

builder.RegisterEntryPointExceptionHandler(ex =>
{
UnityEngine.Debug.LogException(ex);
// Additional process ...
});

If you have multiple EntryPoints, you have the option to use the following declaration as grouping.

builder.UseEntryPoints(entryPoints =>
{
entryPoints.Add<ScopedEntryPointA>();
entryPoints.Add<ScopedEntryPointB>();
entryPoints.Add<ScopedEntryPointC>().AsSelf();
entryPoints.OnException(ex => ...)
});

This is the same as:

builder.RegisterEntryPoint<ScopedEntryPointA>();
builder.RegisterEntryPoint<ScopedEntryPointB>();
builder.RegisterEntryPoint<ScopedEntryPointC>().AsSelf();
builder.RegisterEntryPointExceptionHandler(ex => ...);

See the Plain C# Entry point section for more information.

Register Open Generics

VContainer supports registering open generic types. See Open Generics for more details.