Dependency Injection
Services and Dependency Injection in 3.1.
Starting with Wisej.NET 3.1 we added full support for services and dependency injection. Like everything else in Wisej.NET, it's a very lean, performant, and flexible implementation.
If you need something more complex, we also support switching our IServiceProvider with any third party implementation, including Microsoft's DI, Autofac or others.
Our DI implementation is supported in both .NET 4.8 and .NET 6+.
You can register services at any point in the application. Services are always registered globally so if a service type is registered more than once, subsequent definitions will replace the existing definition.
A good place to initialize the services in the static Program constructor. However, you can register services anywhere else in your code.
static Program() {
// Register an ILogger service implemented by MyLogger as a global shared singleton.
Application.Services.AddService<ILogger, MyLogger>();
// Register an IFileSystem service where the implementation is crated by the CreateFileSystemFactory method
// and scope is set to be the session.
Application.Services.AddService<IFileSystem>(CreateFileSystemFactory, ServiceLifetime.Session);
}
private static IFileSystem CreateFileSystemFactory(Type serviceType) {
return new MyFileSystemImplementation();
}
The code above registers 2 services.
One is an ILogger implementation. Wisej.NET will create an instance if MyLogger only once (Global scope) the first time it's used. This service will never be disposed, if it implements IDisposable, because it's registered using the Shared lifetime making it a singleton instance used by all sessions.
The second line registers a service of type IFileSystem and delegates the creation of the implementation to the CreateFileSystemFactory method, and sets the scope to Session. In this case, Wisej will invoke CreateFileSystemFactory the first time the service is requested per session. The service instance will be automatically disposed, if it implements IDisposable, at the end of the session.
Your code can request a service implementation in three ways:
- Using Application.Services.GetService<T>().
- Using the [Inject] attribute on a property.
- Adding a service argument to the constructor of another service implementation.
Application.GetService<T>() returns the service implementation for the requested T type, if it exists, or null. You can call it at any time.
Using the [Inject] attribute works by default only on top-level UI containers: Page, Form, and Desktop classes. When you add the [Inject] attribute to a property (either protected, private or public), Wisej.NET will automatically resolve the service and assign it to the property during the construction of the object.
public class MyFileSystemImplementation : IFileSystem {