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

时间:2017-08-24 11:18:10

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

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

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

services.AddDbContext<DataContext>(options =>     
    options.UseSqlServer(Configuration["ConnectionStrings:LocalConnectionString"]));

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

1 个答案:

答案 0 :(得分:5)

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

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

在主Startup中,您可以通过扩展名添加图书馆服务。

public class Startup {

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

        services.AddMyLibraryDbContext(Configuration);

        services.AddMvc();
    }
}
相关问题