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

左心房为你撑大大i 提交于 2019-12-12 10:55:38

问题


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();
}

回答1:


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.



来源:https://stackoverflow.com/questions/34910589/is-there-a-way-to-have-asp-net-5-dependency-injection-resolve-a-dbcontext-withou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!