c#依赖注入接口和隐藏内部

时间:2013-11-23 09:24:03

标签: c# interface dependency-injection

我正在尝试重构项目中的某些类,以使用接口和依赖注入使它们可测试。但我在努力解决以下问题:

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用来确定应该发生什么。在所有其他情况下,内部属性设置为默认值,例如当YetAnotherMethod从AnotherConcretObject以外的任何其他类调用时。

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

1 个答案:

答案 0 :(得分:1)

有几种可能的解决方案,具体取决于您的具体操作:

1如果SomePublicMethod是公开的,但SomeOtherMethod是内部的,那么不要将它们放在同一个类中,它们可能会做很多不同的事情,因此关注点分离原则可以发挥作用。 2如果ConcreteObject没有状态并且没有引起副作用,或者你不打算并行运行测试,即具有单位行为,那么它可能不需要模拟,所以访问它直接