How can I run an IHostedService separate from the WebApplication (WebApi)? - c#

Suppose I have a number of IHostedService implementations with a ton of dependencies that no WebApi controllers do not have direct nor indirect dependencies, too.
Ideally, I like it if could set up an IoC container just for the IHostedService (Isolated microservices using containers is not an option for me).
One option is that I could rip out the internals from https://github.com/dotnet/extensions/blob/494e2c53cd/src/Hosting/Hosting/src/Internal/Host.cs
and start up my own non-web-related host, but if I could avoid it if someone with experience could please enlighten me 🙏

The asp.net core web host is built on top of the generic host.
You can separate how you configure your core services from your web specific services. You could also use command line arguments to decide what services to configure, within the same binary.
Though I would recommend moving your services to another library, writing helper functions to register all their dependencies, then building multiple executables for hosting web / backend services.

Related

Azure Function App & Web API in same solution

I need a both a Web API project and a function app project which share the same services / class libraries etc. A few questions
Is it bad practice to place them both in the same solution (or should they be in seperate repositories
Should the services be registered in the Startup class of the Web Api or the function app, or a mixture of the 2? Is it okay to register services only used by the function app in the web api startup class as this would make life easier? The services will do similar things and in some cases the same services will be used by both.
I am likely to only require a few timer trigger functions, most of the application will be build on the web api.
Specifically, the rest API will serve a frontend UI and the function app will provide updates to products on timer triggers.
Thanks for any guidance in advance and apologise if these are silly questions!
For #1 - I think it's totally fine to have them both in the same (git) repository - you might be following a monorepo strategy, OR these projects might be closely related e.g. part of the same business domain/capability where you might have something like a a core Web API project (ASP.NET Core WebApi) as well as some Function App event handlers (in a Function App project) that respond to external async events and invoke the core Web API. Alternatively, if they're completely unrelated repos and you're not following a monorepo strategy then maybe they should be in separate repos.
For #2 - some services might be exclusive to the ASP.NET Core WebApi, some exclusive to the Function App, and some might be shared. Assuming all the code is in the same repo; for the shared dependencies, you might consider having a third 'class library' project in the same git repo that can be referenced by both the ASP.NET Core WebApi project as well as the Function app project. This 'class library' project could contain all the shared dependencies. Dependencies should be registered in the startup of both the Web Api AND the function app.

Dependency injection ASP.Net Core in a WPF application

I have a ASP.NET Core 2.0 project with a lot of dependency injection.
I'm working also on a WPF app (.NET Framework 4.8), and I would like to use a service implemented in the ASP.NET project.
Is it possible t do that in a few lines of code ? And how can I use it ?
This service requires a lot of other service, and it will be long to instanciate each services one by one.
Thanks !
You can always create a new service collection in which you then register your services. You can then build the collection to a service provider and use that resolve your service and have it automatically provide the dependent services:
var services = new ServiceCollection();
// add your services
services.AddSingleton<MyService>();
services.AddTransient<Dependency1>();
services.AddTransient<Dependency2>();
// build service provider
var serviceProvider = services.BuildServiceProvider();
// resolve the service from the service provider
var service = serviceProvider.GetService<MyService>();
Ideally, you would do the setup of the service provider only once at some very early and central location in your app. For example, WPF’s App.xaml.cs or something and store it statically so other components can access the service provider to resolve this and other services.
For registering your services and its dependencies, you can also follow the common pattern of creating reusable extension methods that register a set of related services. For example, you could do this and then use that method in both ASP.NET Core and your WPF application:
public IServiceCollection AddMyServices(this IServiceCollection services)
{
services.AddSingleton<MyService>();
services.AddTransient<Dependency1>();
services.AddTransient<Dependency2>();
return services;
}
You can then just call services.AddMyServices() to add all these services to your service collection.
That being said, using dependency injection in WPF is actually something that has been covered by a number of frameworks already. These will usually not use the dependency injection container from ASP.NET Core (simply because those framework usually predate ASP.NET Core) but have similar ones with similar features. These WPF frameworks also often come with a good setup for MVVM and a lot of specific WPF-related helpers. Example frameworks (without any recommendation from my side) would be Caliburn.Micro, MVVM Light, or Prism.

What is different Between "IWebHost" and "IWebHostBuilder" in Dot Net Core? [duplicate]

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.

use owin to self host web api

I'm self hosting web api using owin on client-server application based on MVC architecture. I see a lot of code examples that shows that the Startup class with the configuration, and the Program class with the Main method that start the owin self host "using (WebApp.Start(url: baseAddress))" - are at the same project. Should I desperate owin self host to one project so the WebApp.Start will be in one project, and web api with Startup claas to another one, with all the controllers and so?
The common answer is that it depends. Usually self host applications is very simple to provide some simple functionality. In that case since both parts are simple there is no need to separate them (host code and Asp.Net Mvc) and they can be placed in one project as an application layer. But if you are trying to add some complexity to host code (e.g. some warm up of Asp.Net Mvc app), then may be you should split your host code and Asp.Net Mvc app code in to two projects.
Found that it might be good idea inspired by separation of concerns: the self host should not know about the server and the opposite. Owin and web api have different job so they need to be separated.

Encapsulating multiple WCF services into a class library

I have one WCF service with multiple endpoints. Each endpoint has it's own configuration.
My problem is that I'm trying to figure out what will be the best.
1 - Add to my MVC application a service reference to each of the endpoints
2 - Create new DLL that will have the references to each of the endpoints and then add in my MVC application a reference only to this DLL.
I could really use your help to figure if there are any downsides to each of the approaches?
UPDATE
i forgot to mention that i have multiple MVC applications and each one uses only one or two of the WCF services.
to be more accurate, i now have 6 MVC applications and 7 WCF services. each MVC application uses only 2 WCF.
in the future the number of MVC apps and WCF will grow.
I would not use a server reference but just point svcutil to all three at the same time. It will generate one set of proxies and one configuration. It also allows you to share data contracts between the services.
Personally, I always put my web references and service references in a standalone assembly called SharedServices. That way; multiple assemblies can share the same references and datatypes can be shared among assemblies. Attaching a web reference to an assembly could lead to many projects being dependent on that assembly solely for the web service defintions.
You can write a service agent that is responsible for accessing the services, abstracting away this logic for your MVC application. The service agent would also be the place to implement other logic like caching, if you would ever need it. See http://tinyurl.com/cbcepgl, below under 'service agent' for some demo code.

Categories