ASP.NET Core 依赖注入

4
在我的asp.net core解决方案中,我有两个项目:asp.net应用程序和包含模式仓库的模型层库。
我请求在应用程序中使用DI实现我的接口。
services.AddTransient<IRepositrory, Repository>();

但是!仓库构造函数有参数

public Repository(string connectionString)
{
    _appDBContext = new AppDBContext(connectionString);
}

如何正确地配置 DI 以从 appsettings.json (asp.net 应用程序) 创建具有特定字符串的存储库?

4
你的仓储类应该将 AppDbContext 注入为依赖项。你现在所拥有的不是正确的 DI 设计。 - MikeSW
公共存储库(IDBContext dbContext),类似这样吗? - Nikishkin Sergey
4个回答

4

有一个接受实现工厂的重载

services.AddTransient<IRepository>(isp => new Repository(conn));

您可以使用以下方式获取连接字符串:
Configuration.GetConnectionString("DefaultConnection")

3
您可以使用AddInstance方法:
var connectionString=Configuration.GetConnectionString("DefaultConnection");
services.AddInstance<IRepository>(new Repository(connectionString));

但我同意@MikeSW在以上评论中所说的话。您应该注册您的DbContext并将其作为参数在您的存储库构造函数中使用:

 services.AddDbContext<AppDBContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

你的构造函数将是:

public Repository(AppDBContext context)
{
    _appDBContext = context;
}

0

你应该将服务放在Startup.cs文件的ConfigureServices方法中。

    public Startup()
    {
        var builder = new ConfigurationBuilder()
                        .AddJsonFile("appsettings.json");
        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<MyDbContext>(
            options => options.UseSqlServer(Configuration["database:connection"]));
     }

appsettings.json文件在哪里:

{
"database": {
"connection":  "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MyDb"
   }
 }

0
services.AddTransient<IRepository>(isp => new Repository(connection));

使用此代码接受实现工厂,并检索连接字符串使用以下代码:

Configuration.GetConnectionString("DefaultConnection") 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接