2

我有一个包含以下项目的分层应用程序:

  • DAL(将 EntityFramework 与存储库一起使用)
  • DAL.Model(包含实体,并被所有其他实体引用)
  • 服务
  • 用户界面(在 wpf 中)

基本存储库如下所示:

public abstract class RepositoryBase<T> where T : class
{
    private readonly MyContext context;
    private readonly IDbSet<T> dbSet;

    protected RepositoryBase(MyContext dataContext)
    {
        context = dataContext;
        dbSet = context.Set<T>();
    }

    protected MyContext Context
    {
        get { return context; }
    }

    **And a series of virtual methods for Add, Delete, etc.
}

所有存储库都扩展了这个,例如:

public class MarketRepository : RepositoryBase<Market>
{
    public MarketRepository(MyContext dataContext) : base(dataContext)
    {

    }

    public IEnumerable<Market> GetAllMarkets()
    {
        return this.Context.Markets.ToList<Market>();
    }
}

服务如下所示:

public class MarketService
{
    IMarketRepository _marketRepository;

    public MarketService(IMarketRepository marketRepository)
    {
        _marketRepository = marketRepository;
    }

    public IEnumerable<Market> GetAllMarkets()
    {
        return _marketRepository.GetAllMarkets();
    }
}

我想要实现的是 UI 层只有对服务层的引用,服务层只有 DAL 层(并且所有这些都到模型,实体所在的模型)使用 DI(现在我使用统一)。

问题是,在我的 UI 容器中,我只想这样做

unity.RegisterType<IMarketService, MarketService>();

并且不必对存储库也这样做,因为这样 UI 层将依赖于 DAL 层。

我考虑向服务类添加一个无参数构造函数,例如:

public MarketService() : this(new MarketRepository(*What would I put here?)) { }

但是后来我失去了接口提供的抽象,而且我不知道如何处理存储库需要作为参数的 MyContext ;如果我通过一个新的,那么我需要参考 DAL。

我应该更改我的存储库以在构造函数中创建一个新的 MyContext,而不是将其作为参数获取吗?

如何重构我的架构以使其正常工作并具有最小的依赖关系?

4

4 回答 4

1

好吧,我相信在更高级别的应用程序中配置依赖项取决于引导程序。因为它通常是 UI 项目,如果它需要引用其他程序集,就这样吧。如果你不喜欢你的 UI 项目管理它,那么创建一个引导程序项目来负责让你的应用程序运行并将你的 UI 类分离到另一个中。

于 2012-11-22T11:52:51.833 回答
0

配置 DI 时,您应该遵循相同的模式 - UI 引导程序初始化服务,服务初始化 DAL。(使用 autofac 或 ninject,您可以使用模块来实现这一点。使用统一,您应该模拟模块)。

在伪代码中类似于

//ui
void UILayer.ConfigureUnity(unity)
{
    ServiceLayer.ConfigureUnity(unity)
}
//services
void ServiceLayer.ConfigureUnity(unity)
{
    DAL.ConfigureUnity(unity)
    unity.RegisterType<IMarketService, MarketService>();

}
//dal
void DAL.ConfigureUnity(unity)
{
    unity.RegisterType<IMarketRepository, MarketRespository>();
    unity.RegisterType<MyContext, MyContext>(); //not sure exact syntax - just register type for 'new Type()' activator.
}
于 2012-11-25T07:42:10.343 回答
0

您的 IoC 容器应该支持使用来自外部配置文件的字符串进行依赖注入。这样您就不会对映射进行硬编码。Structuremap 在这方面做得很好,所以我相信其他 IoC 也会。

于 2012-11-22T11:54:52.617 回答
0

在创建实例时添加外部依赖项作为参数是可行的方法。
我认为您应该让自己更熟悉配置 Unity 的不同方法,以便解决依赖关系。
您能否详细说明在使用依赖注入框架时为什么要创建存储库?

于 2012-11-22T12:04:22.513 回答