How to use Singleton class injected by .NET MVC Ninject?

我与影子孤独终老i 提交于 2019-12-25 16:26:25

问题


I have some problem with InSingletonScope().

My interface:

public interface ISettingsManager
    {
        ApplicationSettings Application { get; }
    }

and my class:

public class SettingsManager : ISettingsManager
    {
        private readonly IConfigurationService _configurationService;

        private readonly Lazy<ApplicationSettings> _applicationSettings;
        public ApplicationSettings Application { get { return _applicationSettings.Value; } }

        private SettingsManager(IConfigurationService context)
        {
             _configurationService = context;

            _applicationSettings = new Lazy<ApplicationSettings>(() => new ApplicationSettings(context));
        }
}

and binding looks like this:

kernel.Bind<ISettingsManager>().To<SettingsManager>().InSingletonScope();

What do you think about this approach?

For example, in HomeControler, when I'm add:

[Inject]
SettingsManager _settingsManager;

the _settingsManager is always null.

How I can use SettingsManager singleton in another project? I always get null.


回答1:


What do you think about this approach?

InSingletonScope() - Only a single instance of the type will be created, and the same instance will be returned for each subsequent request. The dependency will have same scope as of Kernel i.e. Disposed when the Kernel is Disposed.

Read about object scopes here.

[Inject]
SettingsManager _settingsManager;

What are you trying to do here? Field injection?

I do not think it is supported. Copied following from official page:

Field Injection is a bad practice, and got cut for minimization as part of the rewrite between v1 and v2. There is no field injection in Ninject v2.

You can use Property or Constructor injection instead.

Property Injection:

[Inject]
public ISettingsManager SettingsManager { private get; set; }

Constructor Injection:

public class HomeController : Controller
{    
    readonly ISettingsManager settingsManager;

    public HomeController(ISettingsManager settingsManager )
    {
        if(settingsManager == null)
            throw new ArgumentNullException("settingsManager is null");

        this.settingsManager = settingsManager;
    }
}



回答2:


You need to change your _settingsManager to have a type of ISettingsManager instead of SettingsManager.

(You're binding ISettingsManager to SettingsManager. This means when Ninject sees a dependency on ISettingsManager it will inject a SettingsManager. If something is directly declared as SettingsManager it won't do anything)



来源:https://stackoverflow.com/questions/31133557/how-to-use-singleton-class-injected-by-net-mvc-ninject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!