Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It has been well documented, how to inject dependencies into services.

Question: But is it (already) possible in ASP.NET Core 2.0 to have the system's DI mechanism automatically inject a service into a method or into a property?

Sidenote: In PHP-Symfony this pattern is called setter injection.

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.

like image 603
B12Toaster Avatar asked Mar 05 '18 14:03

B12Toaster


1 Answers

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.

like image 93
alastairtree Avatar answered Sep 29 '22 15:09

alastairtree