【问题标题】:ASP.NET Core 1 Dependency Injection: Implementation type always nullASP.NET Core 1 依赖注入:实现类型始终为空
【发布时间】:2016-05-10 16:07:27
【问题描述】:

我在Startup 类的ConfigureServices 方法中有以下内容。 我正在添加一个 ToastNotification 的单例实例,它是 IToastNotification 的一个实现。

public void ConfigureServices(IServiceCollection services)
{
   services.AddInstance<IToastNotification>(new ToastNotification()
         {
         });
}

问题是当我在这个方法结束调试的时候观察服务的值时,IToastNotification服务的实现类型是null。因此,当我尝试从控制器中的服务集合中获取 Toastnotification 实例时,它始终为空。

这就是我使用依赖注入获取Toastnotification 的方式

[FromServices]
private IToastNotification ToastNotification { get; set; }

我做错了什么?

【问题讨论】:

    标签: c# dependency-injection asp.net-core


    【解决方案1】:

    不要使用属性注入,它已被移除并且在未来的版本中将不再起作用:https://github.com/aspnet/Announcements/issues/115

    请考虑使用构造函数依赖注入。

    【讨论】:

    • 谢谢。我照你说的做了。我想我需要密切关注所有重大变化。
    【解决方案2】:

    使用构造函数依赖注入,你可以这样做:

    // Register your service.
    services.AddInstance<IToastNotification>(new ToastNotification());
    

    在你的控制器中:

    public class HomeController : Controller
    {
        private readonly IToastNotification _toastNotification;
    
        public HomeController(IToastNotification toastNotification)
        {
            _toastNotification = toastNotification;
        }
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2018-04-05
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多