[英]ASP.NET Core 1 Dependency Injection: Implementation type always null
我在Startup
类的ConfigureServices
方法中包含以下内容。 我加入的单一实例ToastNotification
这是一个实现IToastNotification
。
public void ConfigureServices(IServiceCollection services)
{
services.AddInstance<IToastNotification>(new ToastNotification()
{
});
}
问题是,当我在此方法末尾调试时观察服务的价值时, IToastNotification
服务的实现类型为null
。 因此,当我尝试从控制器中的服务集合中获取Toastnotification实例时,它始终为null。
这就是我使用依赖注入获得Toastnotification
[FromServices]
private IToastNotification ToastNotification { get; set; }
我究竟做错了什么?
不要使用属性注入,它已被删除,并且在以后的版本中将不起作用: https : //github.com/aspnet/Announcements/issues/115 。
相反,请考虑使用构造函数依赖项注入。
使用构造函数依赖注入,您可以执行以下操作:
// Register your service.
services.AddInstance<IToastNotification>(new ToastNotification());
在您的控制器中:
public class HomeController : Controller
{
private readonly IToastNotification _toastNotification;
public HomeController(IToastNotification toastNotification)
{
_toastNotification = toastNotification;
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.