我应该为每个模型创建一个界面吗?

时间:2023-01-17 18:06:13

I'm just getting started with Dependency Injection (DI) using Ninject and am working through my controllers looking to decouple them from my models a bit more.

我刚刚开始使用Ninject进行依赖注入(DI),并且正在通过我的控制器工作,希望将它们与我的模型分离得更多一些。

At the moment, inside of my controllers I am creating an instance of some given model e.g:

目前,在我的控制器内部,我正在创建一个给定模型的实例,例如:

var activitiesModel = new ActivitiesModel();

For each of my models that I've been instantiating in this way, should I extract an interface for these and then use DI to tie these things together?

对于我以这种方式实例化的每个模型,我应该为这些模型提取接口然后使用DI将这些东西绑在一起吗?

An example of where I'm currently doing this is inside my ActivitiesController:

我目前正在执行此操作的示例位于我的ActivitiesController中:

IActivitiesModel _activitiesModel;

        public ActivitiesController(IActivitiesModel activitiesModel)
        {
            _activitiesModel = activitiesModel;
        }

and this is tied together in my global.asax:

这在我的global.asax中绑定在一起:

Bind<IActivitiesModel>().To<ActivitiesModel>();

Is this the correct way to go about doing this? Should I be creating a new interface for each of my models that is instantiated inside of a controller?

这是正确的方法吗?我应该为在控制器内实例化的每个模型创建一个新界面吗?

Cheers for any help and nudges in the right direction :-)

欢呼任何帮助和推动正确的方向:-)

1 个解决方案

#1


5  

It depends on what those models are doing. If they posses data access and manipulation methods then they should be abstracted to weaken the coupling between your controller and data access logic and ease the testing in separation. If they are simply POCO and/or data transfer objects then you don't need to abstract them.

这取决于这些模型正在做什么。如果他们拥有数据访问和操作方法,那么它们应该被抽象化以削弱控制器和数据访问逻辑之间的耦合,并简化分离测试。如果它们只是POCO和/或数据传输对象,那么您不需要抽象它们。

#1


5  

It depends on what those models are doing. If they posses data access and manipulation methods then they should be abstracted to weaken the coupling between your controller and data access logic and ease the testing in separation. If they are simply POCO and/or data transfer objects then you don't need to abstract them.

这取决于这些模型正在做什么。如果他们拥有数据访问和操作方法,那么它们应该被抽象化以削弱控制器和数据访问逻辑之间的耦合,并简化分离测试。如果它们只是POCO和/或数据传输对象,那么您不需要抽象它们。