ASP.NET核心依赖注入

时间:2016-07-08 17:42:03

标签: c# asp.net-core code-injection

在我的asp.net核心解决方案中,我有2个项目:asp.net app和包含模式层的库,其中包含模式库。

我在应用程序中询问DI实现我的界面

services.AddTransient<IRepositrory, Repository>();

但是!存储库构造函数具有参数

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

如何正确配置DI以使用appsettings.json(asp.net app)中的特定字符串创建存储库?

4 个答案:

答案 0 :(得分:4)

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

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

您可以使用

获取连接字符串
Configuration.GetConnectionString("DefaultConnection")

答案 1 :(得分: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;
}

答案 2 :(得分: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"
   }
 }

答案 3 :(得分:0)

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

使用它来接受实现工厂并检索连接字符串使用它: -

Configuration.GetConnectionString("DefaultConnection")