问题描述
我正在尝试使用通用的 Lazy 类来实例化具有 .net 核心依赖项注入扩展的昂贵类.我已经注册了 IRepo 类型,但我不确定 Lazy 类的注册会是什么样子,或者它是否受支持.作为一种解决方法,我使用了这种方法 http://mark-dot-net.blogspot.com/2009/08/lazy-loading-of-dependencies-in-unity.html
I am trying to use the generic Lazy class to instantiate a costly class with .net core dependency injection extension. I have registered the IRepo type, but I'm not sure what the registration of the Lazy class would look like or if it is even supported. As a workaround I have used this method 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
}
控制器:
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());
}
}
推荐答案
这是另一种支持 Lazy
泛型注册的方法,以便可以懒惰地解析任何类型.
Here's another approach which supports generic registration of Lazy<T>
so that any type can be resolved lazily.
services.AddTransient(typeof(Lazy<>), typeof(Lazier<>));
internal class Lazier<T> : Lazy<T> where T : class
{
public Lazier(IServiceProvider provider)
: base(() => provider.GetRequiredService<T>())
{
}
}
这篇关于.net 核心依赖注入是否支持 Lazy<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!