There are following steps for creating interface and use it in a dependency injection:
- Create a new interface in your project. For example, let’s create a simple interface named
ITimeService
:
public interface ITimeService
{
DateTime GetCurrentTime();
}
- Implement the interface in a new class. For example, let’s create a class named
TimeService
:
public class TimeService : ITimeService
{
public DateTime GetCurrentTime()
{
return DateTime.Now;
}
}
- Register the service in the
ConfigureServices
method of yourStartup
class:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ITimeService, TimeService>();
}
In this example, we are registering the TimeService
implementation of the ITimeService
interface as a transient service. This means that a new instance of the service will be created each time it is requested.
- Inject the service into a controller using constructor injection. For example:
public class HomeController : Controller
{
private readonly ITimeService _timeService;
public HomeController(ITimeService timeService)
{
_timeService = timeService;
}
public IActionResult Index()
{
var currentTime = _timeService.GetCurrentTime();
return View(currentTime);
}
}
In this example, we are injecting the ITimeService
instance into our HomeController
using constructor injection. This allows us to use the GetCurrentTime
method of the service inside the Index
action of our controller.
Overall, creating custom interfaces and injecting them into your application is a key aspect of building modular and maintainable ASP.NET Core applications.