Reputation: 2649
I have a class library alone in a solution. This library will be published as a NuGet package.
So, I want to add the library to my project and I have to connect startup of the project to define this:
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration["ConnectionStrings:LocalConnectionString"]));
But there is no startup in my class library project. How can I define this in the library project for my actual projects ?
Upvotes: 4
Views: 6891
Reputation: 247333
Let your library expose an extension point to be able to integrate with other libraries that want to configure your library.
public static class MyExtensionPoint {
public static IServiceCollection AddMyLibraryDbContext(this IServiceCollection services, IConfiguration Configuration) {
services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:LocalConnectionString"]));
return services;
}
}
That way in the main Startup
you can now add your library services via the extension.
public class Startup {
public void ConfigureServices(IServiceCollection services) {
//...
services.AddMyLibraryDbContext(Configuration);
services.AddMvc();
}
}
Upvotes: 11