Dependency injection ASP.Net Core in a WPF application - c#

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.

Related

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

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.

How to resolve instance of IHubContext<T> in my MVC5 controller with Unity

I need to send a SignalR message from within a controller action. The application is written in MVC5 and .net framework 4.6.1, and I use Unity for Dependency Injection.
How can I register the IHubContext<T> implementations so that they can be successfully resolved in the controller's constructor injection?
All articles I have read about SignalR and Unity are about how to inject services to the Hubs but this is not what I need. I need to inject SignalR services (IHubContext<T>) to my controller but I always get resolve errors.
I also don't want to register the Hubs. I want to register the context.

How to use Autofac registration in an ASP.NET Core app?

I'm migrating my ASP.NET Web API project to ASP.NET Core. I use Autofac for DI and I have the following registrations:
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterHubs(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(config);
Now, in ASP.NET Core, do I need to continue registering controllers and filters or are they automatically registered?
And secondly, what is the new way to register SignalR hubs?
I think this Autofac docs is what you are after.
Depends on the version of ASP.NET Core you use, there are different solutions illustrated in the docs.
In terms of SignalR, you could follow this Microsoft docs, and use Populate method provided by Autofac to populate your service collection into ContainerBuilder.

.Net Core 3.0 HTTP Error 500.30 - ANCM In-Process Start Failure When trying to add AddHostedService() in startup class

I'm working with MVC application with VS 2019 using .NET Core 3.0 and I need to include Service worker in my app After adding this line in my Startup class :
I got this error :
I need to know if I can use a Service worked in my MVC application and how can I resolve this problem .
There can be many reasons. Some suggest(ed in earlier versions of .NET Core) to change the Hosting model from In-process to Out-of-process, for example this known issue. You can read more about Hosting models here. In your case it is probably something else.
Now there are some good examples from Microsoft how to implement hosted services written eg. here and here. But it is also important how (when) to register that service.
In my case the background service uses IServiceProvider depdendency injected in its constructor that's why it really did matter on which line i registered the service - probably due to some internal dependencies which i didn't really figure out. Registering in Program.cs like this solved my problem:
.ConfigureServices(services =>
{
services.AddHostedService<YourAwesomeBackgroundService>();
});
You can probably play around with the order of registrations (based on dependencies) in your ConfigureServices method in Startup.cs if you did it that way or try to remove some dependencies to figure out which causes the problem.
If this doesn't solve your problem i suggest to turn on some logging service since there must be some exceptions thrown.

Work with DI in Asp .NET Core Web API

During the controller design I had the following question:
For example I have Controller that inject via constructor few services that work for more endpoints in that controller, further I want to add new functionality and add new endpoint to that controller as the result I need to add new Service injection to that controller, so system will instantiate of this services any time when user will use endpoints from that controller, even if user does not use them.
What a best approach in this situation, should I inject IServiceScopeFactory insted of service via constructor (for those services that used rare in controller), and create service instances directly in endpoint method ?
Thank for any advice !
UPD: For injection I use native Asp.Net Core mechanism

Categories