how to use scoped dependency in a singleton in C# / ASP

前端 未结 1 1058
春和景丽
春和景丽 2021-01-20 12:08

I\'m new to C#/ASP coming from a Java world. I\'ve read this article: https://docs.asp.net/en/latest/fundamentals/dependency-injection.html#service-lifetimes-and-registratio

相关标签:
1条回答
  • 2021-01-20 12:29

    ok, found it:

    public class Provider<T> : IProvider<T> {
        IHttpContextAccessor contextAccessor;
        public Provider(IHttpContextAccessor contextAccessor) {
            this.contextAccessor = contextAccessor;
        }
        T IProvider<T>.Get() {
            return contextAccessor.HttpContext.RequestServices.GetService<T>();
        }
    }
    

    and in Startup:

        public void ConfigureServices(IServiceCollection services) {
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<ISingletonService, SingletonService>();
            services.AddScoped<IScopedService, ScopedService>();
            services.AddTransient<IProvider<IScopedService>, Provider<IScopedService>>();
            // other bindings
        }
    

    :)

    see https://github.com/aspnet/Hosting/issues/793 for more details about using and registering HttpContextAccessor

    0 讨论(0)
提交回复
热议问题