I have following repository classes:
public class TestRepository : Repository<Test>
{
private TestContext _context;
public TestRepository(TestContext context) : base(context)
{
_context = context;
}
}
public abstract class Repository<T> : IRepository<T> where T : Entity
{
private TestContext _context;
public Repository(TestContext context)
{
_context = context;
}
...
}
public interface IRepository<T>
{
...
}
How do I implement the dependency injection in ASP.NET Core in my Startup.cs
?
I implemented it like this:
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
But then I get following error:
Cannot instantiate implementation type 'Test.Domain.Repository
1[T]' for service type 'Test.Domain.IRepository
1[T]'.
You have to register the dependencies in IServiceCollection in startup class. ASP.NET Core supports the constructor Injections to resolve the injected dependencies. Here, register the interface and their implementation into DI, using the add method of different lifetimes.
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.
Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.
Repository<T>
is an abstract class, so you cannot register it as an implementation, because abstract class simply cannot be instantiated. Your registration would work fine if Repository<T>
was not abstract.
If you cannot make repository class non-abstract, you can register specific implementation of your repository class:
services.AddScoped(typeof(IRepository<Test>), typeof(TestRepository));
This will correctly inject dependencies to your controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With