Created
February 11, 2014 18:03
-
-
Save cvbarros/8940440 to your computer and use it in GitHub Desktop.
Ninject Singleton with Provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternatively, you could use
kernel.Bind<ISingleton>().ToProvider<ConcreteSingletonProvider>().InSingletonScope()
.