简体   繁体   English

DbContext,要注入还是不注入?

[英]DbContext, To Inject or To not Inject?

This may well be a question with a million answers but it is bugging me a lot. 这可能是一个有上百万个答案的问题,但是却困扰着我很多。

I have an mvc application using EF. 我有一个使用EF的mvc应用程序。 Now do I inject the DbContext into my business objects or do I do it some other way? 现在将DbContext注入到业务对象中还是以其他方式进行?

I can obviously inject it but that way I end up using DbContext in my classes rather than a Typed Context. 我显然可以注入它,但是那样一来,我最终在类中使用了DbContext而不是Typed Context。 This means I have no intellisense and the code looks less graceful 这意味着我没有智能感知,代码看起来不太优美

eg 例如

var test=(from d in context.Set<User>() where d.Username=="testname" select d).FirstOrDefault();

compared to the typed loveliness 比起打字的可爱

var test=(from d in context.Users where d.Username=="testname" select d).FirstOrDefault();

Now I know this is not a massive issue but when writing tens of thousands of lines it is nice to have intellisense around, especially if other coders not so familiar with the code are helping out. 现在我知道这不是一个大问题,但是在编写成千上万的行时,最好具有智能感知能力,尤其是在其他不太熟悉该代码的编码人员提供帮助的情况下。

I know there is the unit of work pattern but this is in my opinion the work of the devil himself when EF is involved as it is effectively wrapping a repository pattern in a repository pattern which is just ludicrous. 我知道有工作单元模式,但是在我看来,这是参与EF时魔鬼本人的工作,因为它有效地将存储库模式包装在一个可笑的存储库模式中。 So this is not an option for me. 所以这不是我的选择。

So do we inject and if so can we somehow end up with a typed context? 那么我们是否进行注入,如果可以的话,是否可以以某种类型的上下文结束?

Or do we not inject? 还是我们不注射?

Firstly, I think there might be some misunderstanding in the term 'inject'. 首先,我认为“注入”一词可能会有误解。

Inject means this: 注入意味着:

public class UserService
{
    MyContext _db;

    public UserService(MyContext db)
    {
        _db = db;
    }

    public void GetUserById(string id)
    {
        _db.Users.First(x => x.Id = id);
    } 
}

Instead of this: 代替这个:

public class UserService
{
    MyContext _db = new MyContext();

    public UserService()
    {
    }

    public void GetUserById(string id)
    {
        _db.Users.First(x => x.Id = id);
    } 
}

Notice how in the first example MyContext is 'injected' into the constructor. 注意在第一个示例中,如何将MyContext “注入”到构造函数中。 In the second example, UserService itself creates a new instance of MyContext . 在第二个示例中, UserService本身创建了MyContext的新实例。

Now, should you? 现在,你应该吗? I believe you should, and in fact, it is an accepted good practice. 我相信您应该这样做,实际上,这是一种公认​​的良好做法。 Before you do, make sure to read and try it on a few sample projects to find out the benefits it brings you. 在您这样做之前,请务必阅读并在一些示例项目上进行尝试,以了解它带来的好处。 Wikipidia: Dependency Injection Advantages Wikipidia:依赖注入的优势

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

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