c# 依赖注入(inject)与接口(interface)和隐藏内部

标签 c# interface dependency-injection

我正在尝试重构项目中的一些类,使它们可以使用接口(interface)和依赖注入(inject)进行测试。但我遇到以下问题:

public interface IInterfaceA 
{
   void SomePublicMethod();
}

public class ConcreteObject : IInterfaceA
{
   public void SomePublicMethod() { ... }
   public void SomeOhterMethod() { ... }
   public void YetAnotherMethod() { ... }
}

public class AnotherConcreteObject 
{
    private IInterfaceA _myDependency;
    public AnotherConcreteObject( IInterfaceA myDependency )
    {
       _myDependency=myDependency;
    }
}

到目前为止一切都很好,非常标准的代码。 AnotherConcreteObject 需要调用 SomeOtherMethod,但我不希望其他类(例如在不同的程序集中)能够调用 SomeOtherMethod。所以外部 SomePublicMethod 应该是可见的,但 SomeOtherMethod 不应该是。只有 AnotherConcreteObject 的实例才能调用 SomeOtherMethod。 SomeOtherMethod 将例如设置一个内部属性,稍后 YetAnotherMethod 使用它来确定应该发生什么。在所有其他情况下,内部属性设置为默认值,例如当从 AnotherConcretObject 以外的任何其他类调用 YetAnotherMethod 时。

当不使用接口(interface)时,这是可能的,因为 AnotherConcreteObject 与 ConcreteObject 在同一个程序集中,因此它可以访问内部属性和方法。不同程序集中的类无法设置此属性或调用该方法,因为它们无权访问内部属性和方法。

最佳答案

有几种可能的解决方案,具体取决于您在做什么:

1 如果SomePublicMethod 是公共(public)的,但是SomeOtherMethod 是内部的,那么不要把它们放在同一个类中,它们可能做的事情非常不同,所以分离关注原则开始发挥作用。 2 如果 ConcreteObject 没有状态并且不会引起副作用,或者如果您不打算并行运行针对它的测试,即具有单元行为,那么它可能不需要模拟,所以直接访问它。

关于c# 依赖注入(inject)与接口(interface)和隐藏内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20160660/

相关文章:

C# MongoDB 按日期分组(聚合)

c# - 如何使用 Simple Injector 有条件地注册一个集合?

android - 由于类转换异常,Dagger 2 注入(inject)失败

c# - 按名称或类型比较更快?

c# - 下载多个文件的更快方法

c# - 我应该使用反射 (C#) 组合接口(interface)实现吗?

java - EJB 中的静态工厂方法

java - 注入(inject)设置还是加载一次全局查找?

c# - 如何查看.net网站版本?

go - 与返回自身的方法接口(interface)