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

前端 未结 1 1055
春和景丽
春和景丽 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 : IProvider {
        IHttpContextAccessor contextAccessor;
        public Provider(IHttpContextAccessor contextAccessor) {
            this.contextAccessor = contextAccessor;
        }
        T IProvider.Get() {
            return contextAccessor.HttpContext.RequestServices.GetService();
        }
    }
    

    and in Startup:

        public void ConfigureServices(IServiceCollection services) {
            services.TryAddSingleton();
            services.AddSingleton();
            services.AddScoped();
            services.AddTransient, Provider>();
            // other bindings
        }
    

    :)

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

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