简体   繁体   English

混合封装和依赖注入

[英]Mixing encapsulation and dependency injection

I have a class that serves as a data model. 我有一个充当数据模型的类。 I'll simplify it like this: 我将这样简化:

public class DataModel
{
   public bool IsDataModelActive {get; internal set;}
}

So the programmers who will use my DLL will only see what they need without risking to break anything. 因此,使用我的DLL的程序员只会看到他们需要的内容,而不会冒险破坏任何东西。

On the flipside, I want to use DI in my classes that use DataModel . 另一方面,我想在使用DataModel类中使用DI。 So I have to create an interface: 所以我必须创建一个接口:

public interface IDataModel
{
   bool IsDataModelActive {get;}
}

And so I inject this in my class: 所以我在课堂上注入了这个:

public class Class1
{
   IDataModel dataModel;

   public Class1(IDataModel dataModel)
   {
      this.dataModel = dataModel
   }
}

In this case, it is impossible for me to access the setter of dataModel.IsDataModelActive. 在这种情况下,我不可能访问dataModel.IsDataModelActive的设置器。

The best patch I've found is to cast after receiving the injection: 我发现最好的补丁是在接受注射后进行投射:

public class Class1
{
   DataModel dataModel;

   public Class1(IDataModel dataModel)
   {
      this.dataModel = (DataModel)dataModel
   }
}

This helps for the unit tests, but it kind of break the whole concept of DI. 这对单元测试有所帮助,但是有点打破了DI的整个概念。 What if I have another class that implements IDataModel ? 如果我还有另一个实现IDataModelIDataModel办?

What strategy do you/would you use? 您/您将使用什么策略?

If the interface IDataModel doesn't allow you to access the setter from outside of the DataModel, then (hopefully not surprisingly) you shouldn't need to access the setter from outside of the DataModel. 如果接口IDataModel不允许您从DataModel外部访问设置器,那么(希望这并不奇怪)您不需要从DataModel外部访问设置器。 Either the DataModel itself or something that can see the setter should be responsible for setting that value. DataModel本身或可以看到setter的对象都应负责设置该值。

Is Class1 publicly visible - ie exposed to the consumers? Class1是否公开可见-即向消费者公开? If not, then create another internal interface IDataModelInt : IDataModel and provide setter there. 如果不是,则创建另一个内部接口IDataModelInt:IDataModel并在那里提供设置器。 Use the second one for your internal work. 将第二个用于内部工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM