Is there a way for ASP.NET 5 Dependency Injection to resolve DbContext without reference?

I am making several prototypes with MVC 6 and have run into difficulties. Our project architecture is quite simple:

Data Layer (Entity Framework 6)
Service level (class library, reference data level)
Presentation level (MVC 4, service level links, not a data level reference)

I try to keep the design as similar as possible to the original, even after reading (and agreeing) the structure of the root structure . This means that my new MVC 6 application does not know about my DbContext type. You can guess what happens when I try to enter one of my service classes into a controller:

Unable to resolve service for type My.Data.Tier.DbContext while attempting to activate My.Service.Tier.SomeService.

I believe that our previous implementation (I did not write it) allows DbContext by displaying assemblies in the bin folder. Is there a way I can do this (or something like that) with the new Microsoft.Extensions.DependencyInjection namespace that is built into ASP.NET 5 / MVC 6 so that I can avoid hard linking to my data layer from my presentation level?

Update
After reading Joe Audette's answer, I came up with a very simple extension method that I added to my service level:

 public static class ServiceCollectionExtensions { public static void RegisterDbContext(this IServiceCollection services) { services.AddScoped<My.Data.Tier.DbContext, My.Data.Tier.DbContext>(); } } 

Then in my MVC application Startup.cs:

 using My.Service.Tier.ExtensionNamespace; public void ConfigureServices(IServiceCollection services) { services.RegisterDbContext(); } 
+5
source share
1 answer

I think that in the built-in DI, everything you need should be registered with the DI services.

To save data references from your MVC application, you may have a service level extension method IServiceCollection that registers dbcontext or, in turn, can call a data level extension method.

Thus, your mvc application should have a service level link.

+7
source

Source: https://habr.com/ru/post/1241077/


All Articles