Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DI not resolving base Interface from sub-Interface

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! :(
like image 395
Gerard Wilkinson Avatar asked Jan 26 '26 02:01

Gerard Wilkinson


1 Answers

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.

like image 124
nvoigt Avatar answered Jan 28 '26 17:01

nvoigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!