gpt4 book ai didi

c# - LightInject 在 MVC 中的数据库上下文

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:14 25 4
gpt4 key购买 nike

我开始在我的 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# - LightInject 在 MVC 中的数据库上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com