我开始在我的 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/