2

I have a bunch of services that use dependency injection to inject a collection of objects like this:

IRepository<Games> gamesRepo

this allows the services to use this method without supplying the this IRepository<Games> repo parameter:

GetSingleGame(this IRepository<Games> repo, GameType type) => repo.Query().Single(p => p.GameType == type); 

They can do it like this:

var games = GamesRepo.GetSingleGame(GameType.RPG);

because IRepository<Games> is already supplied via dependency injection.

But I have one controller that needs to use the above method without dependency injection. Is there a way to do this?

When I try to use it like I do above (var games = GamesRepo.GetSingleGame(GameType.RPG);), I get this error:

IRepository does not contain a definition for GetSingleGame

How can I construct IRepository<Games> gamesRepo outside of using dependency injection?

7
  • 2
    Check if the controller contains a using statement to the namespace where the GetSingleGame extension method is defined. Commented Jun 1, 2022 at 17:43
  • @ChristianHeld thank you for responding, it does not, would that work if I added that? Commented Jun 1, 2022 at 17:46
  • 1
    Yes, that's how extensions methods work, see learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… for details Commented Jun 1, 2022 at 17:50
  • 2
    There is no connection between DI and your question. At least I can't see it. Commented Jun 1, 2022 at 20:21
  • 2
    If your question is how to obtain an instance of IRepository without injecting it into the controller's constructor, then you need to create it manually using the new operator. But it's not clear how you are calling var games = GamesRepo.GetSingleGame(GameType.RPG); if you don't have an instance? Who is GamesRepo then? And why you can't inject it into this specific controller? What's special about it? Commented Jun 1, 2022 at 20:28

1 Answer 1

2

You can use ActivatorUtilities to retrieve the instance from dependency injection. Like so:

GetSingleGame(GameType type) => ActivatorUtilities.CreateInstance<IRepository<Games>>() .Query().Single(p => p.GameType == type); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.