Dependency Injection
- 4 minutes to read
Building and maintaining hybrid applications that combine multiple technologies (for example, WinForms, Blazor, ASP.NET Core, .NET MAUI) requires managing dependencies (for example, services, data access layers, or configuration objects) across different layers and platforms. Dependency Injection (DI) simplifies this process.
In hybrid apps, DI allows you to inject shared services and business logic into platform-specific components, and register dependencies in one location.
DI frameworks (for example, Autofac, Ninject, Microsoft.Extensions.DependencyInjection) introduce containers that manage dependency creation and lifecycle, making it easier to write decoupled, testable, and modular code.
Best Practices
- Keep dependency registrations in a common place for easier maintenance.
- Use interfaces in the shared project.
- Encapsulate platform-specific logic to avoid coupling.
Register Dependencies
The following code snippet from our example uses the Autofac DI framework to register OrderDataService
and ReportService
services and resolve dependencies:
using Autofac;
using Autofac.Features.ResolveAnything;
//...
static void Main() {
// Creates an Autofac container builder, which is used to register types and instances with the DI container.
ContainerBuilder builder = new ContainerBuilder();
// Registers the ReportService class with the DI container.
// Configures the service as a singleton (the same instance will be shared across the application).
builder.RegisterType<ReportService>().As<IReportService>().SingleInstance();
// Registers an instance of the OrderDataService class with a pre-configured HttpClient.
builder.RegisterInstance<IOrderDataService>(new OrderDataService(new HttpClient() {
BaseAddress = new Uri("https://localhost:7033/"),
Timeout = new TimeSpan(0, 0, 10)
}));
// Builds the DI container. The container holds all registered services and can resolve dependencies.
container = builder.Build();
MVVMContextCompositionRoot.ViewModelCreate += (s, e) => {
// Resolves the type and injects its dependencies.
e.ViewModel = container.Resolve(e.RuntimeViewModelType);
};
Application.Run(new OrdersForm());
}
The MVVMContextCompositionRoot.ViewModelCreate
event is part of the DevExpress MVVM Framework. The example handles the ViewModelCreate
event to create POCO (Plain Old CLR Object) ViewModels at runtime. Read the following help topic for additional information: ViewModel Management.
Inject Dependencies
Declare a constructor that accepts previously registered interfaces so that the DI container can inject required parameters when creating the ViewModel.
public class OrdersViewModel {
readonly IOrderDataService DataService;
readonly IReportService ReportService;
public OrdersViewModel(IOrderDataService dataService, IReportService reportService) {
DataService = dataService;
ReportService = reportService;
InitDataLoading();
}
//...
}
Share Business Logic & Services
Implement shared business logic and services in a common library:
namespace Client.Shared {
public interface IOrderDataService {
Task<List<Order>> GetOrdersAsync();
}
public class OrderDataService : IOrderDataService {
readonly HttpClient client;
public OrderDataService(HttpClient httpClient) {
client = httpClient;
}
public async Task<List<Order>> GetOrdersAsync() {
List<Order> orders = null;
try {
HttpResponseMessage response = await client.GetAsync("api/Orders");
if (response.IsSuccessStatusCode) {
orders = await response.Content.ReadAsAsync<List<Order>>();
}
}
catch (Exception) {
}
return orders;
}
}
}
Hybrid Project Templates
The DevExpress cross-IDE Template Kit for .NET includes project templates designed to streamline hybrid application development. You can create a desktop application that integrates responsive JavaScript or Blazor components. You can also prototype a shared WinForms & .NET MAUI application that runs seamlessly across multiple platforms.
Hybrid project templates include:
- Shared WinForms & .NET MAUI Application
- Creates both desktop (WinForms) and mobile (.NET MAUI for iOS/Android) applications with a shared presentation and data layer(entity model, business logic, and data service). The application supports Dependency Injection and MVVM architectural patterns.
- Blazor Hybrid WinForms Application
- Creates a hybrid desktop (WinForms) application with a BlazorWebView-powered form and DevExpress themes/styles. The application supports Dependency Injection and integrates the DevExpress Blazor Grid (requires a subscription that includes Blazor UI components).
- JavaScript Hybrid WinForms Application
- Creates a hybrid desktop (WinForms) application with a WebView2-powered form and DevExpress themes/styles. The application supports Dependency Injection and integrates the DevExtreme JavaScript HTML Editor (requires a subscription that includes DevExtreme).
- HTML Hybrid WinForms Application
- Creates a hybrid desktop (WinForms) application with a list and detail forms powered by the DevExpress HTML & CSS engine and reusable UI Templates. The rendering and templating engines allow you to make advanced UI customizations in HTML format, and customize the appearance of UI elements using CSS styles (size, padding, and layout options).
- OData-based Application
- Creates a desktop (WinForms) application with a secure data layer powered by ASP.NET Core OData, EF Core, and XAF’s Backend Web API Service (requires the Universal subscription). With this additional layer of protection (authentication, authorization, and encryption), desktop UI clients cannot access database connection information or modify database tables directly.
- MVVM Application
- Creates a desktop (WinForms) application with a separate presentation layer, entity model, and business logic. The application supports Dependency Injection, MVVM, and Repository architectural patterns. MVVM integration is powered by the DevExpress MVVM Framework or Microsoft CommunityToolkit.Mvvm.
Read the following help topic for additional information: Template Kit for WinForms.
Examples
- Share Code Between Desktop and Mobile Projects (Example)
- Blazor AI Chat in WinForms, WPF, .NET MAUI Apps