简体   繁体   English

设计依赖注入和重用单个数据上下文

[英]Designing Dependecy Injection and reuse of a single data context

I'm currently just starting to implement Dependency injection so I can start testing my code and have come across an issue many of times that I can't figure out. 我目前刚刚开始实现依赖注入,所以我可以开始测试我的代码并且多次遇到一个我无法弄清楚的问题。

My current case scenario: 我目前的情况:

I have a single class ( foo.cs ) that is active the whole time a windows service is running. 我有一个单独的类(foo.cs),它在Windows服务运行的整个过程中都是活动的。 Its responsible for polling the db for new messages then sending them out and update the db to reflect the success of the send. 它负责轮询数据库以获取新消息,然后将其发送出去并更新数据库以反映发送的成功。

My issue is that foo.cs has a dependency for the data access (Message Repository - a linq-to-sql data context) so its injected via the constructor and its life time scope is the same as foo. 我的问题是foo.cs具有数据访问依赖性(Message Repository - linq-to-sql数据上下文),因此它通过构造函数注入,其生命周期范围与foo相同。 Everywhere I'm reading it says that a data context lifetime should be a single unit of work. 我正在阅读的所有地方都说数据上下文生命周期应该是一个单独的工作单元。 So its like I need to inject the actual type I want to use and constructed it every time I want to do a single unit of work in foo rather than passing in a already constructed Repository that stays alive for the entire duration of the service. 因此,我需要注入我想要使用的实际类型,并在每次我想在foo中执行单个工作单元时构造它,而不是传入已经构建的存储库,该存储库在整个服务期间保持活动状态。

One possibility: Don't give the Foo class a data context directly during construction, but rather give it a data context 'factory' class/interface that implements a method that creates a fresh data context on each invocation. 一种可能性:不要在构造期间直接为Foo类提供数据上下文,而是为其提供数据上下文“工厂”类/接口,该类实现了在每次调用时创建新数据上下文的方法。

**EDIT** **编辑**

In case my description is unclear, here's a sketch of what I mean: 如果我的描述不清楚,这里是我的意思草图:

interface IDataContextFactory
{
    ??? CreateContext();
}

class DataContextFactory : IDataContextFactory
{
    public ??? CreateContext()
    {
        // Create and return the LINQ data context here...
    }
}

class Foo
{
    IDataContextFactory _dataContextFactory;

    public Foo(IDataContextFactory dataContextFactory)
    {
        _dataContextFactory = dataContextFactory;
    }

    void Poll()
    {
        using (var context = _dataContextFactory.CreateContext())
        {
            //...
        }
    }
}

This reference discusses various alternatives. 参考文献讨论各种替代方 If your processing is effetively a sequence of all-or-nothing UOWs then a global context may actually be OK. 如果您的处理是有效的一系列全有或全无UOW,那么全局上下文实际上可能是正常的。 If you have greater complexity then then approaches such as the per-thread or factory in the referenced articles may be more appropriate. 如果您具有更高的复杂性,那么引用文章中的每个线程或工厂等方法可能更合适。 In the latter case you would inject the factory rather than the context. 在后一种情况下,您将注入工厂而不是上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM