Author : MD TAREQ HASSAN | Updated : 2020/05/05

Setup DI in aspnet core

Create Interface
IFoo.cs

public interface IFoo
{
    Task<Foo> GetFoo(int id);
}

Implement Interface
FooRepository.cs

public class FooRepository : IFoo
{
    public async Task<Foo> GetFoo(int id)
    {
    
        // ... ... ...
        
        return await ...;
    }
}

Register to DI container
Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // ... ... ...
    
    services.AddScoped<IFoo, FooRepository>(); // AddSingleton, AddTransient

    // ... ... ...
}

Constructor injection

ProductService.cs

public class ProductService
{
    private readonly IFoo _fooRepository;
    
    public ProductService(IFoo fooRepository)
    {
        _fooRepository = fooRepository;
    }
    
    public void DeleteFoo(int id)
    {
        _fooRepository.Delete(id);
    }
}

Registering DBContext

Startup.cs

public void ConfigureServices(IServiceCollection services)
{

    services.AddDbContext<FooDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("FooDBConnection")));
   
    // ... ... ...
}

Details: using-dbcontext-with-dependency-injection

Register multiple services in extension method

ServiceExtensions.cs

public static class ServiceExtensions
{
    public static IServiceCollection RegisterServices(
        this IServiceCollection services)
    {
        services.AddTransient<ITopicAreaService, TopicAreaService>();
        
        // Add all other services here.
        return services;
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.RegisterServices(); // using extension method to register all DI related classes
    
    // Add framework services.
    services.AddMvc();
}