我试图使用通用的Lazy类来实例化.net核心依赖注入扩展的昂贵类.我已经注册了IRepo类型,但我不确定Lazy类的注册是什么样的,或者它是否支持.作为一种解决方法,我使用了这种方法http://mark-dot-net.blogspot.com/2009/08/lazy-loading-of-dependencies-in-unity.html
配置:
public void ConfigureService(IServiceCollection services)
{
services.AddTransient<IRepo, Repo>();
//register lazy
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class ValuesController : Controller
{
private Lazy<IRepo> _repo;
public ValuesController (Lazy<IRepo> repo)
{
_repo = repo;
}
[HttpGet()]
public IActionResult Get()
{
//Do something cheap
if(something)
return Ok(something);
else
return Ok(repo.Value.Get());
}
}
Run Code Online (Sandbox Code Playgroud) c# dependency-injection lazy-initialization .net-core asp.net-core