使用依赖关系解析程序是否会导致性能下降?



我找到了几篇文章,概述了为什么应该避免使用C# MVC中的依赖解析程序

但我也发现了一种将"基本依赖项"注入构造函数的模式,并且该类基本上包含应用程序依赖项的所有实例,但显然不是在每次重新实例化依赖项时 sigleton 中

// example possibly to be avoided
public interface IBaseDependencies
{
IClientRepo ClientRepo { get; }
IProductRepo ProductRepo { get; }
/// more here
}

..但是虽然我喜欢以这种方式传递依赖项的简单性,但问题是所有 deencies 都会被实例化,但它们可能不是全部需要的,所以为了避免性能影响,我想像这样添加 C# 的Lazy<>类......

// Is this example any better?
public interface ILazyBaseDependencies
{
#region IClientRepo
private readonly Lazy<IClientRepo> ClientRepoLazy =
new Lazy<IClientRepo>(() => DependencyResolver.Current.GetService<IClientRepo>());
public IClientRepo ClientRepo => ClientRepoLazy.Value;
#endregion  
/// more here
}

所以现在依赖关系只有在直接调用时才实例化。项目越大,"基本依赖项"方法就越有用,但这样做会损害性能吗?

我不会称之为模式,而是一种代码气味。至少,它违反了接口隔离原则以及依赖反转原则。

会损害性能吗?只有你能回答这个问题。

相关内容

最新更新