{"id":699,"date":"2019-08-26T13:56:31","date_gmt":"2019-08-26T16:56:31","guid":{"rendered":"https:\/\/benjaminray.com\/codebase\/?p=699"},"modified":"2019-08-29T16:20:46","modified_gmt":"2019-08-29T19:20:46","slug":"add-entity-framework-dbcontext-as-service-dependency-injection-in-asp-net-mvc-core-2","status":"publish","type":"post","link":"https:\/\/benjaminray.com\/codebase\/add-entity-framework-dbcontext-as-service-dependency-injection-in-asp-net-mvc-core-2\/","title":{"rendered":"Add Entity Framework DbContext As Service (Dependency Injection) in ASP.Net MVC Core 2"},"content":{"rendered":"<p>This example demonstrates how to add an Entity Framework Core database context as a service using Dependency Injection (a form of Inversion of Control) in ASP.Net MVC Core 2, with an example of referencing the context from an MVC Controller. This example uses a connection string stored in the Development configuration file <code>appsettings.Development.json<\/code>.<\/p>\n<p>Some notes:<\/p>\n<ul>\n<li>Microsoft recommends using the Repository pattern to further abstract the database access layer, in which case we would use the interface IProductsDb in the Dependency Injection instead of the concrete class ProductsDb. However, I've concluded after some research that the Repository Pattern is an unnecessary abstraction when using Entity Framework Core or even Entity Framework 6. <a href=\"https:\/\/benjaminray.com\/codebase\/why-repository-pattern-with-entity-framework-is-no-longer-necessary\/\" rel=\"noopener noreferrer\" target=\"_blank\">Read more about that here.<\/a><\/li>\n<li>The code below only works when you have the Microsoft.EntityFrameworkCore NuGet package installed. If you are using .Net Core 3, you may also need to have the Microsoft.EntityFrameworkCore.SqlServer NuGet package installed.<\/li>\n<li>These instructions are based on using Entity Framework Core in ASP.Net MVC Core 2. If you are using Entity Framework 6, the process is slightly different. Check out <a href=\"https:\/\/docs.microsoft.com\/en-us\/aspnet\/core\/data\/entity-framework-6?view=aspnetcore-2.2\" rel=\"noopener noreferrer\" target=\"_blank\">these instructions<\/a>.<\/li>\n<\/ul>\n<p>While some instructions suggest using <code>services.AddScoped()<\/code> to inject a DbContext as a dependency, <code>services.AddDbContext()<\/code> provides the same service lifetime (lifetime of a single request) and also gives you the ability to configure the service in the function call. More details about the advantages of using <code>services.AddDbContext()<\/code> over <code>services.AddScoped()<\/code> can be found in <a href=\"https:\/\/stackoverflow.com\/a\/42717179\/4669143\" rel=\"noopener noreferrer\" target=\"_blank\">this StackOverflow answer<\/a>.<\/p>\n<p>ConfigureServices method in <code>Startup.cs<\/code>:<\/p>\n<pre><code>\/\/ This method gets called by the runtime. Use this method to add services to the container.\npublic void ConfigureServices(IServiceCollection services) {\n\n    string connectionString = Configuration.GetConnectionString(\"DefaultConnection\");\n    services.AddDbContext&lt;ProductsDb&gt;(options =&gt; options.UseSqlServer(connectionString));\n    services.Configure&lt;CookiePolicyOptions&gt;(options =&gt; {\n        \/\/ This lambda determines whether user consent for non-essential cookies is needed for a given request.\n        options.CheckConsentNeeded = context =&gt; true;\n        options.MinimumSameSitePolicy = SameSiteMode.None;\n    });\n\n    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);\n}\n<\/code><\/pre>\n<p>Controller <code>CategoryController.cs<\/code>:<\/p>\n<pre><code>public class CategoryController : Controller {\n\n    private readonly ProductsDb context;\n\n    public CategoryController (ProductsDb context) {\n        this.context = context;\n    }\n\n    public IActionResult Index() {\n        List&lt;Category&gt; AllCategories = context.Categories.ToList();\n        return View(AllCategories);\n    }\n\n}\n<\/code><\/pre>\n<p>Connection String in <code>appsettings.Development.json<\/code>:<\/p>\n<pre><code>{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Debug\",\n      \"System\": \"Information\",\n      \"Microsoft\": \"Information\"\n    }\n  },\n  \"ConnectionStrings\": {\n    \"DefaultConnection\": \"Server=(localdb)\\\\MSSQLLocalDB;Database=HumanResources;Trusted_Connection=True\"\n  }\n}\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>This example demonstrates how to add an Entity Framework Core database context as a service using Dependency Injection (a form of Inversion of Control) in ASP.Net MVC Core 2, with  [&#8230;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[19,22],"tags":[],"class_list":["post-699","post","type-post","status-publish","format-standard","hentry","category-entity-framework","category-mvc"],"acf":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p9GNjN-bh","jetpack_likes_enabled":false,"_links":{"self":[{"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/posts\/699","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/comments?post=699"}],"version-history":[{"count":12,"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/posts\/699\/revisions"}],"predecessor-version":[{"id":733,"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/posts\/699\/revisions\/733"}],"wp:attachment":[{"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/media?parent=699"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/categories?post=699"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/benjaminray.com\/codebase\/wp-json\/wp\/v2\/tags?post=699"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}