I have a rather simple setup for a repository design. Using DI to resolve repositories in controller constructors.
However DI is behaving rather strangely. It appears to be unable to resolve a dependency which is resolved as the base of a registered interface. I believe it should be able to do this as any type that satisfies the sub-interface must also satisfy the base.
Interested to know if anyone knows why this may be happening?
Example:
Base Interface
public interface IReadOnlyRepository<T>
{
void DoSomething();
}
Sub Interface
public interface IReadWriteRepository<T> : IReadOnlyRepository<T>
{
void DoSomethingElse();
}
Implementation
public class AccountRepository: IReadWriteRepository<Account>
{
public void DoSomething() { /* BLAH */ }
public void DoSomethingElse() { /* BLAH */ }
}
Registration
services.AddTransient<IReadWriteRepository<Account>, AccountRepository>();
Resolution
provider.Resolve<IReadWriteRepository<Account>>(); // SUCCEEDS :)
provider.Resolve<IReadOnlyRepository<Account>>(); // FAILS! :(
That is not how dependency injection works. If you want IReadOnlyRepository<Account> to resolve to AccountRepository you will have to register that, too.
services.AddTransient<IReadOnlyRepository<Account>, AccountRepository>();
Otherwise, how would the DI container know what to generate. Imagine what you have in mind would actually work, what would happen if you would ask it to resolve IDisposable or IEnumerable? It cannot magically know what you need, you have to be explicit.
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