基于事件监听器从集中类调用存储库?

发布于 2024-11-14 04:32:28 字数 270 浏览 2 评论 0原文

我有一个处理(虚拟)汇票交易的程序,并且有许多类具有要求将数据保存到数据库的逻辑。我的问题是,我是否应该直接从各个类调用我的存储库,或者是否应该引发 DatabaseManager 类对象可以侦听的事件,因此所有存储库都将从这一类调用。

我没有使用数据库和存储库的经验,因此希望在这里获得一些更深入的见解和技巧。比如您会选择不同的方法等标准。

值得注意的是,在这种情况下,数据库不用于检索数据以执行程序逻辑,程序启动时除外。因此,它基本上将所有数据保存在运行时对象中,然后转储到数据库进行存档。

I have a program that deals with (virtual) money order transactions, and there are many classes that has logic requiring data to be saved to a database. My question is if I shall call my repositories directly from the various classes, or if I shall instead raise events, which a DatabaseManager class object can listen to, and hence all repositories will be called from this one class.

I don't have experience working with databases and repositories, so would appreciate some deeper insight and tips here. Like on what criteria you would chose different approach etc.

It's probably important to note that the database in this case is not used to retrieve data for performing program logic, except on program startup. So it's basically keeping all data in runtime objects, and just dumping to database for archiving.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晌融 2024-11-21 04:32:28

我会将一个 IRepository 传递给我的类,然后它们可以调用它来保存数据。一方面,它使测试变得更容易,因为您可以轻松地注入模拟存储库,另一方面,它明确表明您的类具有这样的依赖关系。您可能想要搜索术语依赖注入

简单的例子:

class Account
{
    public Account(IRepository<Account> repository)
    {
        _Repository = repository;
    }

    public void ChangeOwner(Owner newOwner)
    {
        // change ownership
        _Repository.Save(this);
    }
}

I would pass an IRepository to my classes which they can then call to save data. For one thing it makes testing easier because you can easily inject a mock repository and on the other hand it makes it explicit that your classes have a dependency like that. You might want to search for the term Dependency Injection.

Simple example:

class Account
{
    public Account(IRepository<Account> repository)
    {
        _Repository = repository;
    }

    public void ChangeOwner(Owner newOwner)
    {
        // change ownership
        _Repository.Save(this);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文