In this article, you will learn about implementing Dependency Injection in Startup.cs in .Net Core.
This article demostrate Dependecy Injection (DI) in Startup.cs in .Net Core. Here for demo purpose, one factory class, database context and a manager class has been created. Let see one by one.
We created a demo db context and named "MyDBContext"
public class MyDBContext { }
Let's create IFactory interface and Factory class. For now, no method has been added and that can be added later. Initialize constructor and add dbcontext and logger object.
public interface IFactory
{
//method signature here
}
public class Factory : IFactory
{
ILogger _logger;
MyDBContext _dbContext;
public Factory(MyDBContext dbContext, ILogger<Factory> logger)
{
_logger = logger;
_dbContext = dbContext;
}
}
Now create a manager class and initialize constructor. Add factory and logger object.
public interface IManager
{
//Signature here
}
public class Manager : IManager
{
ILogger _logger;
IFactory _factory;
public Manager(IFactory factory, ILogger<Manager> logger)
{
_logger = logger;
_factory = factory;
}
}
Now go to Startup.cs class and add below code in Configuration method.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFactory, Factory>(sp =>
{
var logger = sp.GetRequiredService<ILogger<Factory>>();
var dbContext = sp.GetRequiredService<MyDBContext>();
return new Factory(dbContext, logger);
});
services.AddTransient<IManager, Manager>(sp =>
{
var factory = sp.GetRequiredService<IFactory>();
var logger = sp.GetRequiredService<ILogger<Manager>>();
return new Manager(factory, logger);
});
}
Another way to define is that simply add all dependecy constructors like below.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration["DbContext:CONNECTION_STRING"];
services.AddDbContext<MyDBContext>(opts => opts.UseNpgsql(connectionString), ServiceLifetime.Transient);
services.AddTransient(typeof(ILogger<>), typeof(Logger<>));
services.AddTransient<IFactory, Factory>();
services.AddTransient<IManager, Manager>();
}
Here connection string for database is defined in appsettings.json fileHope this helps you.