To use, first install 'Microsoft.Extensions.DependencyInjection' package in our project.
To register the interfaces and objects, use either AddTransient(), AddScoped() or AddSingleton() methods. Their lifetimes are:
- AddTransient - new instance is created each time requested
- AddScoped - new instance is created per client request/session
- AddSingleton - created once only through application life, subsequent requests will access the same instance
Then we use GetService() method to get an instance.
An example of how to use the tool in a unit test:
[TestClass] public class ExampleTest { private readonly IStudentRepository studentRepository; public ExampleTest() { var services = new ServiceCollection(); services.AddTransient<IStudentRepository, StudentRepository>(); var serviceProvider = services.BuildServiceProvider(); studentRepository = serviceProvider.GetService<IStudentRepository>(); . . . } }
To use it in different projects, we can create an extension method of IServiceCollection in the particular project. For example, in service project:
public static class IServiceCollectionExtension { public static IServiceCollection AddServicesConfiguration(this IServiceCollection services) { services.AddTransient<IStudentService, StudentService>(); return services; } }and in repository project:
public static class IServiceCollectionExtension { public static IServiceCollection AddRepositoriesConfiguration(this IServiceCollection services) { services.AddTransient<IStudentRepository, StudentRepository>(); return services; } }Some people like to do this approach but then a project that wants to use the extension method(s) needs to directly reference the other project(s). For example; a web project will need to reference service and repository projects.
Personally, I prefer to create a bootstrap project that contains all DI mappings and has references to all projects needed. Then a project just need to reference the bootstrap project.
In this example, the WebAPI project just need to reference Bootstrap project, not Service and Repository projects.
All DI configurations are in one place:
public static class BootstrapConfig { public static IServiceCollection RegisterRepositories(this IServiceCollection services) { services.AddTransient<IStudentRepository, StudentRepository>(); return services; } public static IServiceCollection RegisterServices(this IServiceCollection services) { services.AddTransient<IStudentService, StudentService>(); return services; } }
No comments:
Post a Comment