小编BLa*_*ars的帖子

使用.NETCore进行DAL和连接字符串的依赖注入

我是使用.NETCore的DI模式的新手,我无法将连接字符串连接到DAL.

我通过接受的答案和随后的评论遵循了这个帖子中给出的建议.

这是我的基类

public class BaseRepository : IRepository<IDataModel>
{
    private readonly IConfiguration config;

    public BaseRepository(IConfiguration config)
    {
        this.config = config;
    }

    public string GetSQLConnectionString()
    {
        return config["Data:DefaultConnetion:ConnectionString"];
    }
Run Code Online (Sandbox Code Playgroud)

这是继承基类的存储库类的片段

public class PrivacyLevelRepository : BaseRepository, IRepository<PrivacyLevelDM>
{
    public PrivacyLevelRepository(IConfiguration config) : base(config) { }
    public void Add(PrivacyLevelDM dataModel)
    {
         ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在我的startup.cs中

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddScoped<IRepository<IDataModel>>(c => new BaseRepository(Configuration));
    }
Run Code Online (Sandbox Code Playgroud)

但是,在我的服务层中,存储库类的实例化仍然要求(IConfiguration配置)作为参数传递.

 PrivacyLevelRepository repo = new PrivacyLevelRepository();
Run Code Online (Sandbox Code Playgroud)

如何将IConfiguration直接加载到我的DAL,而不必从Controller> BLL> DAL传递它.这似乎非常低效,而且不正确.因为DAL应该确定对象的连接,而不是控制器或服务层.他们应该不知道数据源,不是吗?

我认为这很简单,我只是没有在DI/IoC范例中看到,但我无法弄明白.

编辑:我没有使用Entity …

.net dependency-injection asp.net-core

9
推荐指数
2
解决办法
7716
查看次数

标签 统计

.net ×1

asp.net-core ×1

dependency-injection ×1