somecoolname
somecoolname

Reputation: 337

AutoFac inject based on controller

Hi I was wondering if my logic is flawed or if I just can't find the function I have ApiControllers (Address / Article /...) each one has a IRepository

I want to Inject AddressRepository if the baseclass is the AddressController. ArticleRepository if ArticleController and so on. I could do this with Ninject but I wanted to switch because of company standart reasons and performance.. How can I do this with AutoFac? Or do I have a anti pattern?

Upvotes: 0

Views: 124

Answers (1)

Steven
Steven

Reputation: 172606

You should ask yourself what would happen if you inject an ActicleRepository in the AddressController. If this compiles but breakes at runtime, there is something wrong with your design. To be exact, the problem is that you are violating the Liskov substitution principle that states that each sub type (or implementation of an interface) should behave in a way that is compatible with the contract. In other way each implementation should be substitutable from each other without the consumer to notice.

So each repository should have its own abstraction. There are two paths to walk here:

  1. Give each repository its own unique non-generic abstraction, such as IArticleRepository and `IAddressRepository.
  2. Define a generic IRepository<TEntity> abstraction. This way controllers can depend on either IRepository<Article> or IRepository<Address> and you have compile-time support and you are adhering to the LSP.

Upvotes: 1

Related Questions