hadashiA / VContainer

The extra fast, minimum code size, GC-free DI (Dependency Injection) library running on Unity Game Engine.
https://vcontainer.hadashikick.jp
MIT License
2.01k stars 176 forks source link

How to register Open Generic type with factory method #715

Closed slimshader closed 1 month ago

slimshader commented 1 month ago

Let's say I have (not purely hypothetical):

Ilogger<T> LoggerFactory.CreateLogger<T>();

and I want objects to be able to inject specific instance of ILogger direclty like so:

class MyClass
{
   MyClass(Ilogger<MyClass> logger) {}
}

docs have "Register Open Generics" section but I see no Register overload that would allow to pass CreateLogger as a factory method to Register(typeof(Ilogger<>)

hadashiA commented 1 month ago

Try the following:

            var loggerFactory = LoggerFactory.Create(x => x.AddZLoggerUnityDebug());
            builder.RegisterInstance(loggerFactory);
            builder.Register(typeof(Logger<>), Lifetime.Singleton).As(typeof(ILogger<>));

Note:

slimshader commented 1 month ago

Thanks, this indeed solves this case, but what in general?