简体   繁体   English

在 ASP.NET MVC 中使用 ASP.NET Core IServiceCollection

[英]Using ASP.NET Core IServiceCollection in ASP.NET MVC

I am trying to use the ASP.NET Core 2.2 IServiceCollection to build the dependency injection into an ASP.NET MVC (on the full .NET Framework 4.7) app.我正在尝试使用 ASP.NET Core 2.2 IServiceCollection将依赖项注入构建到 ASP.NET MVC(在完整的 .NET Framework 4.7 上)应用程序中。 The reason is that I have an api project built with ASP.NET Core and uses Entity Framework Core, so I want both web app (mvc) and api (core) to use the same framework (EF Core).原因是我有一个使用 ASP.NET Core 构建的 api 项目并使用了 Entity Framework Core,所以我希望 web app(mvc)和 api(core)使用相同的框架(EF Core)。

The problem I am having now is that AddScoped seems to be working as if I used Singleton (ie same dbcontext is being used every time I make a web request)我现在遇到的问题是AddScoped似乎像我使用Singleton一样工作(即每次我发出 Web 请求时都使用相同的dbcontext

Can you give me a hint how to tell the IServiceCollection to use the ASP.NET MVC based request scope instead of the .NET Core one?你能给我一个提示如何告诉IServiceCollection使用基于 ASP.NET MVC 的请求范围而不是 .NET Core 范围吗?

Solved using custom Scope per request:根据请求使用自定义 Scope 解决:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        Context.Items.Add("serviceScope", Startup.Provider.CreateScope());
    }

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        var serviceScope = Context.Items["serviceScope"] as IServiceScope;
        serviceScope?.Dispose();
    }

And

public class DotNetCoreDependencyResolver : IDependencyResolver
{
    private readonly IServiceProvider _serviceProvider;
    private readonly IDependencyResolver _oldDependencyResolver;

    public DotNetCoreDependencyResolver(IServiceProvider serviceProvider, 
        IDependencyResolver oldDependencyResolver)
    {
        _serviceProvider = serviceProvider;
        _oldDependencyResolver = oldDependencyResolver;
    }

    public object GetService(Type serviceType)
    {
        var serviceScope = HttpContext.Current.Items["serviceScope"] as IServiceScope;
        return serviceScope?.ServiceProvider?.GetService(serviceType)
            ?? _serviceProvider.GetService(serviceType) 
            ?? _oldDependencyResolver.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType) 
        => _oldDependencyResolver.GetServices(serviceType);
}

In Startup.cs在 Startup.cs 中

 Provider = services.BuildServiceProvider();
 DependencyResolver.SetResolver(new DotNetCoreDependencyResolver(Provider, DependencyResolver.Current));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM