Download presentation
Presentation is loading. Please wait.
1
Dependency Injection in .Net Core
Achieving Loose Coupling and High Cohesion September 27, 2016
2
What is dependency injection?
Dependency injection is a technique for achieving loose coupling between objects and their dependencies Rather than directly instantiating dependencies, the objects needed for a class are provided to them Most often class will declare their dependencies via their constructor
3
Inversion of Control Containers
It is helpful to have a class dedicated to creating classes and dependencies A container is a factory for providing instances of types that are requested from it .NET Core has a simple built-in container that is represented by the IServiceProvider interface
4
Injection of a Simple Repository
An IStaffRepository is injected into a StaffController constructor The ConfigureServices method of the Startup class is responsible for defining the services the application will use services.AddTransient<IStaffRepository, StaffRepository>();
5
Service Life Times Transient: Services are created every time they are requested Scoped: Services are created once per request Singleton: Services are created the first time they are requested. Each subsequent request uses the same instance
6
Example An operation interface is defined with a with a unique identifier OperationId One type per life time option is created An OperationService is defined which which depends on each of the other operation types It is used to clarify whether the this service is getting the same instance as the controller or a new one
7
Adding These to Configure Services
public void ConfigureServices(IServiceCollection services) { … services.AddTransient<IOperationTransient, Operation>(); services.AddScoped<IOperationScoped, Operation>(); services.AddSingleton<IOperationSingleton, Operation>(); services.AddTransient<OperationService>(); }
8
Resources als/dependency-injection.html pendencyInjectionDemo
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.