【问题标题】:How to add service.AddDbContext in class library .NET CORE如何在类库 .NET CORE 中添加 service.AddDbContext
【发布时间】:2017-08-28 22:54:13
【问题描述】:

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

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

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

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

【问题讨论】:

  • 公开允许访问您的配置的扩展方法。

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


【解决方案1】:

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

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();
    }
}

【讨论】:

  • 非常感谢!
  • 一个小提醒:必须安装Microsoft.EntityFrameworkCore.SqlServer才能在依赖注入中使用options.UseSqlServer扩展。
  • @ŞerefCanMuştu 那是正确的。如果您不想将库绑定/耦合到它,您可以公开配置函数,以便启动将管理它。
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多