Search code examples
c#asp.netblazor-webassembly

How to pass parameters besides injected services in constructor?


In constructor of the Game class, I am passing scoped service ISessionsRepository as an injected service and other parameters.

public class Game 
{
    private ISessionsRepository repo;

    public Game(ISessionsRepository injectedRepo, string sessionID, string sessionName) 
    {
        // *code*
    }
}

I know, this won't work. But I still have to create instance of Game class by using new(). And in the ctor arguments I do not want to pass ISessionsRepository, only sessionID and sessionName:

Game game = new("1", "name");

Solution

  • You can add a new constructor for Game

    public Game(string sessionId, string sessionName) {other code}
    

    EDIT: It looks like my suggestion is an anti-pattern as stated in the first comment of this question.

    In case you still need to access the service, what you can do is to retrieve manually the service that you need from the service container, in the class that is instantiating Game and passing it to Game.

    Here a question that should help you do that.

    If you really don't want to pass it from the outside, you can create the new constructor that I suggested and make it request the Service you need.