Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am doing some prototyping with MVC 6 and have run into a quandary. Our project architecture is straightforward enough:

Data Tier (Entity Framework 6)
Service Tier (Class Library, references Data Tier)
Presentation Tier (MVC 4, references Service Tier, does not reference Data Tier)

I'm attempting to keep the design as similar to the original as possible, even after reading (and agreeing with) the Composition Root pattern. This means that my new MVC 6 application is unaware of my DbContext type. You can guess what happens when I attempt to inject 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 didn't write it) resolves the DbContext by reflecting assemblies in the bin folder. Is there a way I can do this (or something like it) with the new Microsoft.Extensions.DependencyInjection namespace that's built-in to ASP.NET 5/MVC 6 so I can avoid a hard reference to my data tier from my presentation tier?

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

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 app's Startup.cs:

using My.Service.Tier.ExtensionNamespace;

public void ConfigureServices(IServiceCollection services)
{
    services.RegisterDbContext();
}
like image 793
AJ. Avatar asked Jan 20 '16 21:01

AJ.


1 Answers

I think in the built in DI everything you need must be registered with the DI services.

To keep the data references out of your MVC app, you could have an IServiceCollection extension method in your Services tier that would register the dbcontext, or it in turn could call an extension method on the data tier.

That way your mvc app only has to have a reference on the services tier.

like image 118
Joe Audette Avatar answered Oct 09 '22 18:10

Joe Audette