Skip to content

Instantly share code, notes, and snippets.

@cvbarros
Created February 11, 2014 18:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cvbarros/8940440 to your computer and use it in GitHub Desktop.
Save cvbarros/8940440 to your computer and use it in GitHub Desktop.
Ninject Singleton with Provider
void Main()
{
var kernel = new StandardKernel();
kernel.Bind<SomeDependency>().ToSelf();
kernel.Bind<ISingleton>().ToProvider<ConcreteSingletonProvider>();
kernel.Bind<ConcreteSingletonProvider>().ToSelf().InSingletonScope();
var i = kernel.Get<ISingleton>();
var i2 = kernel.Get<ISingleton>();
Console.WriteLine(i.GetId());
Console.WriteLine(i2.GetId());
}
// Define other methods and classes here
internal class ConcreteSingletonProvider : Provider<ISingleton>
{
public IKernel Kernel { get; set; }
//Just a wrapper
private readonly Lazy<ISingleton> _lazy = new Lazy<ISingleton>(() => ConcreteSingleton.Instance);
public ConcreteSingletonProvider(IKernel kernel)
{
Kernel = kernel;
}
protected override ISingleton CreateInstance(IContext context)
{
if (_lazy.IsValueCreated == false)
{
Console.WriteLine("Injecting ISingleton...");
Kernel.Inject(ConcreteSingleton.Instance);
}
return _lazy.Value;
}
}
public class ConcreteSingleton : ISingleton
{
[Inject]
public SomeDependency Dependency { get; set; }
private static readonly Lazy<ConcreteSingleton> _instance = new Lazy<ConcreteSingleton>(() => new ConcreteSingleton());
private ConcreteSingleton()
{
}
public static ConcreteSingleton Instance
{
get
{
return _instance.Value;
}
}
public static ConcreteSingleton GetInstance(IKernel kernelForInjection)
{
if (_instance.IsValueCreated == false)
{
kernelForInjection.Inject(_instance.Value);
}
return _instance.Value;
}
public Guid GetId()
{
return Dependency.Id;
}
}
public interface ISingleton
{
Guid GetId();
}
public class SomeDependency
{
public SomeDependency()
{
Id = Guid.NewGuid();
}
public Guid Id;
}
@zwei0
Copy link

zwei0 commented Apr 3, 2019

alternatively, you could use kernel.Bind<ISingleton>().ToProvider<ConcreteSingletonProvider>().InSingletonScope().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment