简体   繁体   中英

LightInject equivalent lifetime in .netcore DI container

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>())); 

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>()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM