问题
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