1

我已经实现了存储库模式。我有我的基本模型类,它们只不过是标准的 C# 类。我有每个模型的存储库类。我有我的DbContext课。我正在使用 Ninject,所以除了我的模型之外的所有东西都首先定义为接口。现在,要访问我的数据,我的代码如下所示:

using (var context = m_kernel.Get<IPortalContext>())
{
    var accounts = m_kernel.Get<IAccountRepository>(new ConstructorArgument("context", context));

    foreach (var account in accounts.All())
    {
        Assert.IsNotNull(account);
    }
}

注意:我不确定是否有更好的方式来表示我想将该上下文传递给 IAccountRepository 构造函数,但那是另一次了。

如您所见,我的存储库类都需要一个上下文实例。这就是我在相同的上下文中工作的原因,就像一个工作单元一样。

我的问题是,如何为我的业务逻辑引入服务层?现在,我的存储库只有简单的 Get、Delete、All、Insert 方法。我想要一个用于我的特定业务逻辑和验证的服务层。解决这个问题的最佳方法是什么?

乍一看,我可以只创建服务类,就像我的 repo 类一样,接受上下文并执行业务逻辑,然后使用 repo 类。这基本上会将存储库隐藏在一起。

这是一个好方法吗?

4

1 回答 1

1

That is the approach I use. That also would allow you to make your Repositories generic. Here is an example:

Internal class AccountService
{
    Public Account GetAccount(string firstName)
    {
        var results = Enumerable.Empty<Account>();

        try
        {
             var repository = new Repository<Account>(); // I use and interface here and                    
                                                         // then a factory class. I just
                                                         // was trying to keep it simple.
             results = repository.FindAll()
                 .Where(a => a.FirstName == firstName)
                 .ToList();
        }
        catch()... etc.

        return results;
    }
}

Public interface IAccountService
{
    Account GetAccount(string accountNumber);
}

By using this pattern it allows you to mock the results of your repository classes and unit test your Service class methods and then because you are using an interface for your service class you can mock the results of your Service methods when needed if you are unit testing your UI level...

Also I have successfully created generic repository classes for LinqToSql and EntityFramework so I can change frameworks and the rest of the application doesn't care.

于 2013-10-15T23:43:28.737 回答