LightInject equivalent lifetime in .netcore DI container

230 Views Asked by At

Migrating from 'LightInject' to .netcore DI container.

What are the .netcore DI container equivalents of below LightInject related registrations?

 a. container.RegisterConstructorDependency<IBar>((factory, parameterInfo) => new Bar()); 

 b. container.RegisterInstance<Func<string, string>>
        ((username, password) => new MemCache(userId, password, container.GetInstance<IBusinessLogic>())); 
1

There are 1 best solutions below

0
ProgrammingLlama On

I believe A would be something like this:

services.AddTransient<IBar>(container => new Bar());

For B, if you have an instance that already exists that you simply want to register, then you could do something like:

ISomething somethingInstance = new Something();
services.AddSingleton<ISomething>(somethingInstance);

But it seems like you actually want to register a factory, so I would suggest something like this:

services.AddScoped<Func<string, string, MemCache>>(ctx => (username, password) => new MemCache(username, password, ctx.GetRequiredService<IBusinessLogic>()));