ASP.NET Core MVC Dependency Injection via method
It has been well documented, how to inject dependencies into a controller's constructor or in its action methods (via FromServices
attribute).
Question: But is it possible to have the system's DI mechanism automatically inject a service in a method ("parameter injection") that is not an action?
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 (eg 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 redundant.
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.
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.
链接地址: http://www.djcxy.com/p/82104.html上一篇: 主要的C#DI / IoC框架如何比较?