Normally with ASP.NET Core projects, I have access to the IWebHostBuilder creation, upon which I can register services and build configuration, and then I can get into a Startup class where I can inject any of the services or configurations that were registered while building the host. I use this two-stage approach quite often, as I usually need some services available within Startup to finish registering everything else.
Now I'm working on a Generic Host headless app, adding a BackgroundService with AddHostedService<T>. There is no Startup class in this scenario, so it seems all my dependencies have to be registered while creating the HostBuilder. I'm not able to use my normal services because of the lack of the second registration step.
When using the Generic Host/non-HTTP/BackgroundService/AddHostedService approach, how can I get two stages of dependency registration as I do in Web projects?
Related
I want to use background tasks in asp.net core.
I found helpful documentation https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio
I wonder why their lifetime apparently is scoped: Hosted service that activates a scoped service. The scoped service can use dependency injection (DI).
What is a scope in this context?
For web applications, a scoped lifetime indicates that services are created once per client request (connection). Register scoped services with AddScoped.
In apps that process requests, scoped services are disposed at the end of the request.
While I do understand what that means for e.g a standard http get request to an api,
I do not understand the meaning for a background worker.
Imho it would make more sense to have a singleton backgroundworker. I certainly do not want to have multiple instances running at a time in my application.
Another thing is DI in background workers which apparently differs fron standard services:
To use scoped services within a BackgroundService, create a scope. No scope is created for a hosted service by default.
I cannot confirm that:
services.AddHostedService(x => new DataPersister(x.GetRequiredService<IAsyncDocumentSession>(), x.GetRequiredService<ILogger>()));
seems to work just fine.
You have to read the sentence “Hosted service that activates a scoped service” within its full context:
This article provides three hosted service examples:
Background task that runs on a timer.
Hosted service that activates a scoped service. The scoped service can use dependency injection (DI).
Queued background tasks that run sequentially.
(from “Background tasks with hosted services”, emphasis mine)
So it is not the case that hosted services have a scoped lifetime. All hosted services added using AddHostedService() are actually added with a singleton lifetime, ensuring that there will only ever be a single instance of it.
What the article refers to is the situation when you need to consume a scoped service, like a database connection, within a hosted service. Since you cannot inject scoped dependencies into a singleton service, you will need a different solution there. And the solution usually involves having the singleton service (the hosted service in this case) create a service scope itself from which it can then retrieve the scoped dependency.
I went into more details about the service scopes in this recent answer to a similar question if you are interested.
This is mostly an academic question, but it might have some real world value in my project.
Having defined a web host in a web project (dotnet core 3.1), is there any way to call this host directly with a HttpContext?
I assume there might be a service somewhere to override to allow me to just run the HttpContext processing part of the pipeline, without having an actual web server running - but I can't quite find it. Any ideas?
Our project is using multitenancy to resolve some Service, lets say MyService based on SaasKit.
We also have a background task, which shares some of it's dependencies with the asp.net core controllers.
In the background task, any object that depends on MyService will get a null reference.
I can implement workarounds to get instances of MyService, like using service locator pattern, but this approach fails to create classes that depend on MyService without breaking DI and IOC logic.
So the question is: How can I get the same services that I can get from HttpContext with multitenancy, but get them without an HttpCoontext?
I have a set of 7 .Net Framework WebApi-based services that all share some common design elements. One shared element is that each will include the service version in the data that it returns from any of its endpoints. In each service, I determine the version from the executing assembly using reflection. I do this in Application_Start and store the result in a property that I create on the Global class that inherits from System.Web.HttpApplication. That way I do the reflection work once and access the result later from each of my methods.
I'm building a new service and this one is built on ASP.NET Core. So I'm trying to figure out how to do the same thing in ASP.NET Core. I can add the reflection logic in Startup.Configure (though it's not really about configuring the Http pipeline which is what Configure is supposed to be doing). Is there a better place than Startup.ConfigureServices or Startup.Configure, to put code that you want to run once on startup?
And where would I store the result to make it readily accessible to each of the downstream methods called from my controller actions?
After reading Microsoft documents I am still confused. I need to deploy a .net core 2 web application I developed to an IIS server and I can't get a straight forward answer on anything. This is just the beginning of my questions.
What is the difference between IWebHost, WebHostBuilder, BuildWebHost?
Thanks!
First of all, let me start with that I very much disagree with your statement: The documentation on ASP.NET Core is actually very good. Yes, it may be still lacking in some details, and it also has some problems catching up to changes with releases, but overall the content is really good and the team working on it is really doing a remarkable job. It’s really difficult to author a documentation for such a large and fast-moving framework, and the amount of information you get through the documentation is actually very good. You will likely get to recognize that once you have overcome the initial problems in starting with a new framework.
But coming back to your question:
IWebHost: The web host is the general thing that hosts and runs your web application. It gets created when your application starts up, and then it will construct all the necessary pieces, like the Kestrel web server, the application middleware pipeline, and all the other bits, and connects them, so that your application is ready to serve your requests.
The web host is basically the thing that makes up your web application.
IWebHostBuilder: The web host builder is basically a factory to create a web host. It is the thing that constructs the web host but also configures all the necessay bits the web host needs to determine how to run the web application.
With ASP.NET Core 2, you will usually create a “default web host builder” which will already come with a lot defaults. For example, the default web host will set up the Kestrel web server, enable and configure logging, and add support for the appsettings.json configuration.
Usually, your applications will always start with such a default web host and you then just use the web host builder to subsequently configure the web host before it is actually being built.
BuildWebHost is part of the older convention before ASP.NET Core 2.1 where the default pattern in the Program.cs was to build the web host in a separate method. With 2.1, this was changed so that the method would no longer build the web host directly but just create the web host builder (hence the method now being called CreateWebHostBuilder). So basically, the .Build() call on the web host builder was refactored out of the method. You can see this nicely in the migration guide for 2.0 to 2.1.
The reason this was done is to make the CreateWebHostBuilder reuseable. The builder configuration that happens in that method is basically everything that is necessary to configure the web host. So by making that reusable, without generating an actually created web host, it can be used for other purposes. In this case, this was done for integration testing using the TestHost. The test host will basically host the web host internally for your integration tests, and it will do so by looking for the CreateWebHostBuilder method.
With ASP.NET Core 2.1, the default pattern you see in the Program.cs is the following (comments added by me for further explanations):
public class Program
{
// main entry point for your application
public static void Main(string[] args)
{
// create the web host builder
CreateWebHostBuilder(args)
// build the web host
.Build()
// and run the web host, i.e. your web application
.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
// create a default web host builder, with the default settings and configuration
WebHost.CreateDefaultBuilder(args)
// configure it to use your `Startup` class
.UseStartup<Startup>();
}
Btw. this topic is generally covered in the application startup and hosting sections of the official documentation.
ASP.NET Core 3.x
Starting with ASP.NET Core 3.0, there has been a change with the setup I described above. The reason for this is the generic host. The “generic host” is a generalization of the web host and the web host builder, to allow non-web scenarios outside of ASP.NET Core, making ASP.NET Core itself just a “hosted service” that runs on top of the generic host.
IHost: The host is the component that hosts and runs your application and its services. This is a generalization of the previous IWebHost but fullfills basically the same task: It starts configured hosted services and makes sure that your app is running and working.
IHostBuilder: The host builder constructs the host and configures various services. This is the generalization of the previous IWebHostBuilder but also basically does the same just for generic IHost. It configures the host before the application starts.
There is the Host.CreateDefaultBuilder method that will set up a host with various defaults, e.g. configuration using appsettings.json and logging.
IHostedService: A hosted service is a central component that the host hosts. The most common example would be the ASP.NET Core server, which is implemented as a hosted service on top of the generic host.
You can also write your own hosted services, or add third-party services that allow you to nicely add things to your application.
The generic host introduced with ASP.NET Core 3.0 and .NET Core 3.0 basically replaces the previous IWebHost and IWebHostBuilder. It follows the very same architecture and idea but is simply reduced to non-web tasks so that it can work with a number of different purposes. ASP.NET Core then just builds on top of this generic host.