.NET Core中的服务定位器不支持作用域

问题描述 投票:2回答:1

我的部分代码需要使用ServiceLocator,因为不支持构造函数注入。

我的启动类配置服务。我有一些是短暂的,其他的是单身和其他范围。

例如:

services.AddScoped<IAppSession, AppSession>();
services.AddScoped<IAuthentication, Authentication>();
services.AddScoped<NotificationActionFilter>();

在我的服务定义结束时,我有以下代码块,它设置服务定位器。

var serviceProvider = services.BuildServiceProvider();
DependencyResolver.Current = new DependencyResolver();
DependencyResolver.Current.ResolverFunc = (type) =>
{
    return serviceProvider.GetService(type);
};

我注意到在给定的请求中,我没有从构造函数注入的服务定位器接收相同的实例。从服务定位器返回的实例似乎是单例,并且不尊重范围。

DependencyResolver的代码如下:

public class DependencyResolver
{
    public static DependencyResolver Current { get; set; }

    public Func<Type, object> ResolverFunc { get; set; }

    public T GetService<T>()
    {
        return (T)ResolverFunc(typeof(T));
    }
}

我怎样才能解决这个问题?

c# asp.net-core .net-core inversion-of-control service-locator
1个回答
2
投票

我建议创建一个中间件,将ServiceProvider设置为在其他地方使用的中间件:

public class DependencyResolverMiddleware
{
    private readonly RequestDelegate _next;

    public DependencyResolverMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        DependencyResolver.Current.ResolverFunc = (type) =>
        {
            return httpContext.RequestServices.GetService(type);
        };

        await _next(httpContext);
    }
}

此外,应更新DependencyResolver以支持此类行为:

public class DependencyResolver
{
    private static readonly AsyncLocal<Func<Type, object>> _resolverFunc = new AsyncLocal<Func<Type, object>>();

    public static DependencyResolver Current { get; set; }

    public Func<Type, object> ResolverFunc
    {
        get => _resolverFunc.Value;
        set => _resolverFunc.Value = value;
    }

    public T GetService<T>()
    {
        return (T)ResolverFunc(typeof(T));
    }
}

不要忘记在Startup.cs中的Configure方法中注册它:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseMiddleware<DependencyResolverMiddleware>();
}
© www.soinside.com 2019 - 2024. All rights reserved.