Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add service.AddDbContext in class library .NET CORE

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 ?

like image 826
canmustu Avatar asked Jan 04 '23 13:01

canmustu


1 Answers

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();
    }
}
like image 193
Nkosi Avatar answered Jan 08 '23 23:01

Nkosi