简体   繁体   中英

.NET core custom service based on request on Startup

I am following this example of .NET core based on request dependency injection:

https://dotnetliberty.com/index.php/2016/04/11/asp-net-core-custom-service-based-on-request/

I have different implementations of a service based on some http headers and I want to load a specific service depending on request.

In startup.cs I have the following code:

 services.AddDbContext<MyContext>(options => options.UseMysql);

services.AddTransient<IMyService>(serviceProvider =>
            {
                var context = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
                var header = context.Request.Headers["mycustomheader"];
                if (header == "first") return new MyFirstService();
                else return new SecondService();
            });

This is working fine. On every request I get the header and use different implementations of IMyService.

The problem is that I also need to inject the DbContext which I have defined previously and I have no idea how to do it, or if its even possible.

I mean I need to do:

new FirstService(DbContext); instead of new FirstService();
and new SecondService(DbContext); instead of new SecondService();

Is this possible in .NET core?

You need to use DI for that:

var context = serviceProvider.GetRequiredService<MyContext>();

This is the same as what you already do for getting IHttpContextAccessor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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