什么时候将dbcontext服务添加到启动?

问题描述 投票:0回答:1

我在解决方案中有 2 个不同的“设计模式”项目: 1-ChainOfResponsibiltyDesignPattern 和 2-RepositoryDesignPattern :

enter image description here

责任链设计模式的背景 enter image description here

ChainOfResponsibiltyDesignPattern 的启动 enter image description here

RepositoryDesignPattern 的上下文 enter image description here

RepositoryDesignPattern 的开始 enter image description here

我在解决方案中有 2 个不同的“设计模式”项目: 1-责任链设计模式, 2-存储库设计模式。 两者的框架相同,都是5.0。 虽然两者的 dbcontext 类相同,但 ChainOfResponsibiltyDesignPattern 的启动配置文件中不需要“services.AddDbContext();”,而 RepositoryDesignPattern 则需要。

即使两者的 dbcontext 类相同,为什么会发生这种情况? 什么情况下我们必须等待配置中的dbcontext服务?

谢谢。

c# asp.net-core dbcontext
1个回答
0
投票

您似乎拥有

Context
类,但没有进行依赖项注入以在项目“ChainOfResponsibiltyDesignPattern”中使用。
当你想通过“依赖注入”方式创建一个“类”(公共类...)的实例时,你需要将该类注册到服务中。

这意味着当您的项目中存在如下代码(使用依赖注入)时:

    public class xxxxxx 
    {
        private readonly Context context;

        public xxxxxx(Context context)
        {
            this.context = context;
        }
    }

您需要像

Context
一样注册
builder.Services.AddSingleton<Context>();
,但由于
Context
是一个特殊的数据库类,您可以注册使用
builder.Services.AddDbContext<Context>();

参考:https://stackify.com/net-core-dependency-injection/

© www.soinside.com 2019 - 2024. All rights reserved.