3

I'm trying to understand dependency injection in ASP.NET MVC CORE.

All examples are the same, they show to register HttpContextAccessor

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

Then the class that wants to access it:

public class UserService : IUserService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public bool IsUserLoggedIn()
    {
        var context = _httpContextAccessor.HttpContext;
        return context.User.Identities.Any(x => x.IsAuthenticated);
    }
}

But then, when i actually want to create an instance of UserService, it asks for the httpContextAccessor object in constructor, where do i get that from?

2
  • what are you trying ... if you are creating the instance explcitly then you will have to pass the dependency yourself Commented Dec 12, 2018 at 12:52
  • Do i need to inject UserService also? Commented Dec 12, 2018 at 12:55

2 Answers 2

6

When using dependency injection, you are not supposed to actually create any service yourself. To consume your UserService, you should just inject that somewhere as well.

Typically, the flow in ASP.NET Core for your application code starts in a controller. So if you want to use the UserService inside of a controller action, you should inject it into the controller:

public class ExampleController : Controller
{
    private readonly IUserService _userService;

    public ExampleController(IUserService userService)
    {
        _userService = userService;
    }

    public IActionResult Index()
    {
        var isLoggedIn = _userService.IsUserLoggedIn();

        // …

        return View();
    }
}

So you don’t create an instance yourself using new but instead you rely on the dependency injection system to provide you with an instance.

You just need to make sure to register the service inside of the ConfigureServices:

services.AddTransient<IUserService, UserService>();

This principle holds regardless of where you are within your application. Since the entry point is always being created by the system, you are always inside of a dependency injection context, so you can just depend on things which have dependencies themselves (which again could have more dependencies etc).

I would strongly suggest you to read the chapter on dependency injection of the documentation, as it covers the idea very well. It also explains what the different lifetimes mean.

Sign up to request clarification or add additional context in comments.

3 Comments

In ConfigureServices, do i need to Add UserService there? As Singelton?
Yes, in order to use the user service, you would have to register it. You don’t have to use singleton there though. For your own services, you can usually default to a transient lifetime (unless you know you need a different behavior). So you would do services.AddTransient<IUserService, UserService>(); – I would recommend you to check out the dependency injection chapter of the documentation.
Thank you, now i finally understand that i need to inject httpContextAccessor to my service, and then inject my service into my controller.
0

in DI, you normally dont need to create Instance by yourself. Instead you need to register your implemented services to the DI service container and then call it inside your constructor.

This way you eliminates the need for manual instance creation.

services.AddScoped<IMyService, MyService>();

then

class MyConsumerClass
{
    private readonly IMyService _myService;
    MyConsumerclass(IMyService myService)
    {
         _myService = myService;
    }
}

In this way, you don't need to care about what services is needed to be initialized (parameterized) into your constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.