如何在类库.NET CORE中添加service.AddDbContext

can*_*stu 4 c# dependency-injection asp.net-core .net-core-2.0

我在解决方案中只有一个类库.该库将作为NuGet包发布.

所以,我想将库添加到我的项目中,我必须连接项目的启动来定义:

services.AddDbContext<DataContext>(options =>     
    options.UseSqlServer(Configuration["ConnectionStrings:LocalConnectionString"]));
Run Code Online (Sandbox Code Playgroud)

但我的类库项目中没有启动.如何在库项目中为我的实际项目定义它?

Nko*_*osi 6

让您的库公开一个扩展点,以便能够与其他想要配置库的库集成.

public static class MyExtensionPoint {
    public static IServiceCollection AddMyLibraryDbContext(this IServiceCollection services, IConfiguration Configuration) {
        services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:LocalConnectionString"]));
        return services;
    }
}
Run Code Online (Sandbox Code Playgroud)

在主要方面,Startup您现在可以通过扩展程序添加您的图书馆服务.

public class Startup {

    public void ConfigureServices(IServiceCollection services) {
        //...

        services.AddMyLibraryDbContext(Configuration);

        services.AddMvc();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一个小提醒:必须安装`Microsoft.EntityFrameworkCore.SqlServer` 才能在依赖注入中使用`options.UseSqlServer` 扩展。 (2认同)