.NET Core中的服务定位器不支持范围界定

时间:2018-11-28 09:15:34

标签: c# asp.net-core .net-core inversion-of-control service-locator

我的部分代码需要使用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));
    }
}

我该如何解决?

1 个答案:

答案 0 :(得分: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>();
}