0

I have a WinForms application which uses Entity Framework 5.0.

I want to keep the context short-lived by instantiating and disposing it on a user-story basis. For example - user clicks save, then instantiate the context, save, and dispose.

In addition to that, I have a service layer, and I inject the same context to the services.

The issue is that I am ending up with lengthy code in each of my user-story handlers. For example:

void OnSaveButtonClick(object sender, EventArgs e)
{
    using (var context = new MyEntities())
    {
        var transactionService = new TransactionService(context);

        transactionService.SaveTransaction(...);
    }
}

So I am just wondering if there is any pattern (or DBContext's event) that I could use to keep the code "readable" for my client. Much appreciated.

4

1 回答 1

1

您可以通过编写一个获取上下文和事务的函数来重构代码,然后执行您想要的操作。就像是:

// Define a new delegate to handle the various actions
public delegate void UseCasehandler(DbContext context);

void PerformUseCase(UseCaseHandler action)
{
    using (var context = new MyEntities())
    {
        var transactionService = new TransactionService(context);
        action(context);
        transactionService.SaveTransaction(...);
    }
}

然后你的 SaveButtonClick 只会说

PerformUseCase(SaveData);

SaveData与该用例相关的代码在哪里。

void SaveData(DbContext context)
{
    ...
}

现在,这对缩短代码的长度并没有多大作用,但是它将样板文件与执行实际工作的代码分开。

回复:神秘人的评论。如果不需要获取交易,那么这个答案就更没用了。但是,如果事实证明在每个可以移动到PerformUseCase.

于 2013-06-11T20:54:32.497 回答