结构问题:使用依赖注入导致垃圾API [英] Architecture problem: use of dependency injection resulting in rubbish API

查看:145
本文介绍了结构问题:使用依赖注入导致垃圾API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我特林创建一个类,它的确各种低级别的数据库相关的行动,但presents一个非常简单的界面UI层。的

I'm tring to create a class which does all sorts of low-level database-related actions but presents a really simple interface to the UI layer.

本类重presents全部在一个特定的聚合根一组数据,由一个单一的ID INT检索。

This class represents a bunch of data all within a particular aggregate root, retrieved by a single ID int.

的构造函数四个参数:

public AssetRegister(int caseNumber, ILawbaseAssetRepository lawbaseAssetRepository, IAssetChecklistKctcPartRepository assetChecklistKctcPartRepository, User user)
{
  _caseNumber = caseNumber;
  _lawbaseAssetRepository = lawbaseAssetRepository;
  _assetChecklistKctcPartRepository = assetChecklistKctcPartRepository;
  _user = user;
  LoadChecklists();
}

UI层通过接口 IAssetRegister 访问这个类。温莎城堡可以提供ILawbaseAssetRepository和IAssetChecklistKctcPartRepository参数本身,而是UI code需要使用提供另外两个匿名类型是这样的:

The UI layer accesses this class through the interface IAssetRegister. Castle Windsor can supply the ILawbaseAssetRepository and IAssetChecklistKctcPartRepository parameters itself, but the UI code needs to supply the other two using an anonymous type like this:

int caseNumber = 1000;
User user = GetUserFromPage();
IAssetRegister assetRegister = Moose.Application.WindsorContainer.Resolve<IAssetRegister>(new { caseNumber, user});

从视图中的API设计上来看,这是垃圾。 UI层开发人员无法知道该IAssetRegister需要一个整数和一个用户的方式。他们需要了解类,以使用它的实现。

From the API design point of view, this is rubbish. The UI layer developer has no way of knowing that the IAssetRegister requires an integer and a User. They need to know about the implementation of the class in order to use it.

我知道我必须有某种设计问题在这里。任何人都可以给我一些指点?

I know I must have some kind of design issue here. Can anyone give me some pointers?

推荐答案

由于莫滕指出的,移动从构造函数调用方法(S)非注射依赖条件,实际上需要使用它,

As Morten points out, move the non injectable dependecies from the constructor call to the method(s) that actually need to use it,

如果您有构造paramters是不能(或者很难)注射,您将无法autmatically注入 IAssetRegister 进入,要么需要它的任何类

If you have constructor paramters that can't (or are difficult to) be injected you won't be able to autmatically inject IAssetRegister into any class that needs it either.

您总是可以的,当然,创建具有沿着这些路线的具体实施 IUserProvider 接口:

You could always, of course, create a IUserProvider interface with a concrete implementation along these lines:

public class UserProvider : IUserProvider 
{
    // interface method
    public User GetUser() 
    {
        // you obviously don't want a page dependency here but ok...
        return GetUserFromPage();
    }
}

因此​​,创建另一个注射依赖那里有没有。现在你不再需要用户传递到每一个方法可能需要它。

Thus creating another injectable dependency where there was none. Now you eliminate the need to pass a user to every method that might need it.

这篇关于结构问题:使用依赖注入导致垃圾API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆