Ninject注射单例类

Ninject注射单例类

本文介绍了如何使用.NET MVC Ninject注射单例类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题,InSingletonScope()。

I have some problem with InSingletonScope().

我的界面:

public interface ISettingsManager
    {
        ApplicationSettings Application { get; }
    }

和我的类:

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));
        }
}

和结合这个样子的:

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

你怎么看待这种做法?

What do you think about this approach?

例如,在HomeControler,当我补充一下:

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

[Inject]
SettingsManager _settingsManager;

_settingsManager 总是空。

我怎么可以使用设定管理单在另一个项目中?我总是空。

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

推荐答案

您需要更改_settingsManager有型ISettingsManager,而不是设置管理的。

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

(你结合ISettingsManager来设定管理。这意味着,当Ninject上看到ISettingsManager依赖它会注入设定管理。如果事情是直接宣布为设定管理它不会做任何事情)

(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)

这篇关于如何使用.NET MVC Ninject注射单例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:41