Reputation: 828
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 !
Upvotes: 0
Views: 1502
Reputation: 387667
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.
Upvotes: 1