Search code examples
c#dependency-injectionasp.net-core-2.0asp.net-core-mvc-2.0

ASP.NET Core MVC Dependency Injection via property or setter method


Question: It has been well documented, how to inject dependencies into services. However, is it also possible in ASP.NET Core 2.0 to have the system's DI mechanism automatically inject a dependency into a method or into a property? (similar to what is called setter injection in PHP-Symfony).

Example: Say I have a common MyBaseController class for all controllers in my project and I want a service (e.g. the UserManager service) to be injected into MyBaseController that can be later accessed in all child controllers. I could use constructor injection to inject the service in the child class and pass it via base(userManager) to the parent. But having to perform this in all child constructors of all controllers is pretty tedious.

So I would like to have a setter in MyBaseController like this:

public abstract class MyBaseController : Controller
{
  public UserManager<User> userManager { get; set; }

  // system should auto inject UserManager here
  public void setUserManager(UserManager<User> userManager) {
    this.userManager = userManager;
  }
}

...so I don't have to do the following in every child constructor just to pass the dependency to the parent:

public class UsersController : MyBaseController
{
  public ChildController(UserManager<User> userManager) : base(userManager) {}

Update: The answer given here is what I want to achieve, however the question was asked for ASP.NET Core 1.0, I'm interested in whether any solutions have been added in ASP.NET Core 2.0.


Solution

  • In general it is good advice to avoid non constructor DI as it is considered a bit of an anti pattern, there is a good discussion about it in this related question.

    With the default Microsoft.Extensions.DependencyInjection container in aspnet core, the answer is no, but you could swap to something more powerfull like autofac (which has property injection) if you are sure you really need this feature.