gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 中的服务定位器替代方案

转载 作者:行者123 更新时间:2023-12-01 13:12:24 25 4
gpt4 key购买 nike

<分区>

已阅读Mark Seemann's blog post连同 this response引用它,我理解通过类构造函数使用 Service Locator 模式而不是依赖注入(inject)的缺点。我也读过这个Dependency Injection with Ninject, MVC 3 and using the Service Locator Pattern其中也讨论了这个问题。

但是,我的问题与这个特殊情况有关:

public class MyController
{
public void GetData()
{
using (var repository = new Repository())
{
// Use the repository which disposes of an Entity Framework
// data context at the end of its life.
}
}

// Lots of other methods.
}

这里我有一个 Controller ,它包含一个调用存储库的方法,该存储库自动实例化一个内部 Entity Framework 数据上下文。使用这个单一的数据上下文,因为存储库中的每个方法都会调用该上下文,因此在存储库对象的整个生命周期内共享一个单一的上下文似乎是有意义的。

现在,由于 Controller 类很大,很有可能不会使用这个给定的存储库。由于我假设(可能是错误的)这种实例化 DC 是一项昂贵的操作,所以我宁愿避免这样做。使用服务定位器模式允许我将实例化推迟到实际需要上下文时,但考虑到上述链接中反对它的有效参数,我宁愿避免它。

所以我想知道的是,在上述情况下是否有更有效的使用依赖注入(inject)的方法,可以防止我不必要地实例化我的存储库和底层数据上下文。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com