c# - Light在 MVC 中注入(inject)数据库上下文

标签 c# asp.net-mvc entity-framework light-inject

我开始在我的 MVC 应用程序中使用 LightInject,但我对如何实现 DB Context 类的实例有点困惑。

我知道我可以通过构造函数注入(inject)它......但是如果我必须这样做,LightInject 的意义何在。

此外,我的应用程序中的 DB Context 类已经实现了一个接口(interface) (IdentityDbContext),因此为存储库创建另一个接口(interface)似乎并不正确。

DB Context 类的构造函数中确实有这样的内容:

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

所以我可以很容易地调用:

 _context.Create()

在构造函数中 - 但我的理解是,这违背了 SOLID 原则。

那么如何使用 LightInject 创建数据库上下文类的实例呢?

最佳答案

您可以注册上下文,然后通过构造函数注入(inject)传递它:

在你的ioc配置文件中:

container.Register<Context, Context>(new PerScopeLifetime());

一些服务:

private readonly Context _context;

public BookService(Context context)
{
    _context = context;
}

如果你想使用一个接口(interface),那么注册一个接口(interface)并将其传递到你想要的任何地方。

关于c# - Light在 MVC 中注入(inject)数据库上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621223/

相关文章:

c# - 如何控制作为绑定(bind)源的TextBox文本何时更新目标值?

c# - Web API 总是返回内部服务器错误而不是我抛出的错误

c# - 为什么 Entity Framework 在直接 select 语句中比 Dapper 执行得更快

asp.net-mvc - 如何在 ASP.NET MVC 应用程序中设置调试启动页?

jquery - ASP.NET MVC 中带有复选框的 DropDown(组合框)

.net - 在 Entity Framework Code First 中将 Guid 属性映射到 Oracle

mysql - Entity Framework - 具有多个结果集的存储过程 - 没有行返回

asp.net - 服务器向 Web 客户端发送消息的最佳方式是什么?

c# - 学习 Entity Framework 6 命令树拦截器