LittleFunny
LittleFunny

Reputation: 8375

How to inject the service defined during the dependency injection in c#

I have setup the dependency injection in startup.cs say: IAction. In controller, I can inject the service as a parameter in the constructor. But what if my normal class in Business Layer for example, How do that service be injected.

In Microsoft documentation, it is a bad design if do something like the image below:

enter image description here

Is there a better way? If I tried passed these service from controller to other layers, this will not give good result as well.

Upvotes: 0

Views: 560

Answers (1)

Dustin C
Dustin C

Reputation: 265

You should be able to pass the same dependencies through the constructors of the classes in your business layer just like you pass them through the constructors of your controllers in your Web API layer or MVC layer.

Something like this:

public class UsersService
{
    private readonly IUsersRepository usersRepository;

    public UsersService(IUsersRepository usersRepository)
    {
        this.usersRepository = usersRepository;
    }

    public async Task<User> GetUser(int userId)
    {
        return await usersRepository.GetByIdAsync(userId);
    }
}

Upvotes: 1

Related Questions