asp.net核心web api,如何注入连接字符串

时间:2017-12-09 04:16:46

标签: asp.net dependency-injection asp.net-core asp.net-core-2.0

这是我的asp.net核心项目结构

1- ASP.NET CORE Web API (包含aspsettings.json)

"ConnectionStrings": {
    "DefaultConnection": "Server=(local)\\SQLEXPRESS;Database=testdb;Trusted_Connection=True;"

  }

2-SERVICES Project (服务项目的Web API调用方法)
3-REPOSITORY项目(来自Repository Project and Repository Project的服务调用方法包括所有模型所在的DATA项目)

4-DATA项目,其中包含所有带代码的模型

public class TtEntities : DbContext
    {

        public virtual DbSet<RoomMessage> RoomMessage { get; set; }
        public virtual DbSet<UserRoom> UserRoom { get; set; }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
           optionsBuilder.UseSqlServer(@"Server=(local)\SQLEXPRESS;Database=testdb;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
....

正如您所看到的,我对OnConfiguring方法的连接进行了硬编码,这不是最佳实践。

有没有办法从Web API项目的配置文件中传递连接字符串?

如果我们从web api项目传递文件aspsettings.json中的连接,那么update database命令是否仍然有效?

非常感谢

2 个答案:

答案 0 :(得分:1)

DI完美地解决了这个问题,.NET Core 2.0的Microsoft DI提供了明确的DI体验。

哦,让我们开始(我认为DATA Project和REPOSITORY Project应该是一个)

来自REPOSITORY项目 将您的REPOSITORYClass更改为

    public class REPOSITORYClass 
    {
        private readonly TtEntities _db;

        public REPOSITORYClass (TtEntities db){
            _db = db;
        }

        //some your staff of REPOSITORYClass thats uses _db
    }

现在转到服务项目

让我们更改一些使用REPOSITORYClass

的服务
public class SomeService
    {
        private readonly REPOSITORYClass _repo;

        public SomeService (REPOSITORYClass repo){
            _repo = repo;
        }

        //other staff of SomeService thats uses _repo
    }

之后转到ASP.NET CORE Web API启动文件并添加到

  

public void ConfigureServices

        // Get connection of your repo
        string connection = Configuration.GetConnectionString("DefaultConnection");
        // add TtEntities as service
        services.AddDbContext<TtEntities>(options =>
                        options.UseSqlServer(connection));

//add your repo
        services.AddTransient<REPOSITORYClass>();
//add your service
        services.AddTransient<SomeService>();

现在转到使用SomeService的控制器

    public class SomeController: Controller
        {
            private readonly SomeService _someService;

            public SomeController(SomeService someService){
                _someService = someService;
            }

            //And use whatever your wants from your service that injected with deps of repo and injected db entity with connection
            public string SomeMethod()
            {
                 return _someService.SomeMethod();
            }
        }

并使用您的服务中的任何需求,这些服务使用repo deps注入并使用连接注入数据库实体

那就是

PS还建议阅读此Introduction to Dependency Injection in ASP.NET Core

答案 1 :(得分:1)

一个简单的解决方案是这样的:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }
}

考虑第13行中DefaultConnection的使用方式。另外,示例appsettings如下所示:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication5;"
  }
}